如何随机化列顺序的子集
How to randomize a subset of the column order
我有一个数据框,我想随机打乱某些列的顺序。例如,这里有一个例子来表示我所拥有的:
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14
ch1 12 A 9 10 6 5 6 3 4 6 5 7 5
ch2 13 T 7 10 1 7 3 3 3 1 7 8 6
ch3 14 T 5 7 7 2 6 8 1 1 8 1 5
ch4 15 G 8 9 2 7 9 7 7 3 10 10 4
ch5 16 T 8 2 8 2 4 7 1 8 10 3 2
我想保持前三列相同(V1-V3),然后随机打乱其余列的顺序(V4-V14)。例如,
V1 V2 V3 V6 V5 V11 V4 V14 V10 V8 V7 V13 V12 V9
ch1 12 A 6 10 6 9 5 4 6 5 7 5 3
ch2 13 T 1 10 1 7 6 3 3 7 8 7 3
ch3 14 T 7 7 1 5 5 1 6 2 1 8 8
ch4 15 G 2 9 3 8 4 7 9 7 10 10 7
ch5 16 T 8 2 8 8 2 1 4 2 3 10 7
我发现了很多在列中排列行的方法,但还没有遇到任何打乱列顺序的方法。任何帮助,将不胜感激。
您可以单独保留前三列,而将所有其他列打乱
df[c(1:3, sample(4:ncol(df)))]
让我们通过仅返回列名称来了解它如何与 mtcars
一起工作。
replicate(7, names(mtcars[c(1:3, sample(4:ncol(mtcars)))]))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] "mpg" "mpg" "mpg" "mpg" "mpg" "mpg" "mpg"
# [2,] "cyl" "cyl" "cyl" "cyl" "cyl" "cyl" "cyl"
# [3,] "disp" "disp" "disp" "disp" "disp" "disp" "disp"
# [4,] "carb" "am" "hp" "qsec" "am" "am" "am"
# [5,] "wt" "hp" "drat" "carb" "carb" "wt" "carb"
# [6,] "hp" "gear" "vs" "drat" "qsec" "gear" "qsec"
# [7,] "drat" "carb" "am" "vs" "wt" "vs" "hp"
# [8,] "qsec" "vs" "carb" "wt" "gear" "hp" "gear"
# [9,] "vs" "drat" "gear" "am" "drat" "drat" "drat"
# [10,] "am" "wt" "qsec" "gear" "vs" "qsec" "wt"
# [11,] "gear" "qsec" "wt" "hp" "hp" "carb" "vs"
我们可以看到每个 运行 的前三个列名称(此处显示为行)保持不变,而其他的则不同。
我有一个数据框,我想随机打乱某些列的顺序。例如,这里有一个例子来表示我所拥有的:
V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 V11 V12 V13 V14
ch1 12 A 9 10 6 5 6 3 4 6 5 7 5
ch2 13 T 7 10 1 7 3 3 3 1 7 8 6
ch3 14 T 5 7 7 2 6 8 1 1 8 1 5
ch4 15 G 8 9 2 7 9 7 7 3 10 10 4
ch5 16 T 8 2 8 2 4 7 1 8 10 3 2
我想保持前三列相同(V1-V3),然后随机打乱其余列的顺序(V4-V14)。例如,
V1 V2 V3 V6 V5 V11 V4 V14 V10 V8 V7 V13 V12 V9
ch1 12 A 6 10 6 9 5 4 6 5 7 5 3
ch2 13 T 1 10 1 7 6 3 3 7 8 7 3
ch3 14 T 7 7 1 5 5 1 6 2 1 8 8
ch4 15 G 2 9 3 8 4 7 9 7 10 10 7
ch5 16 T 8 2 8 8 2 1 4 2 3 10 7
我发现了很多在列中排列行的方法,但还没有遇到任何打乱列顺序的方法。任何帮助,将不胜感激。
您可以单独保留前三列,而将所有其他列打乱
df[c(1:3, sample(4:ncol(df)))]
让我们通过仅返回列名称来了解它如何与 mtcars
一起工作。
replicate(7, names(mtcars[c(1:3, sample(4:ncol(mtcars)))]))
# [,1] [,2] [,3] [,4] [,5] [,6] [,7]
# [1,] "mpg" "mpg" "mpg" "mpg" "mpg" "mpg" "mpg"
# [2,] "cyl" "cyl" "cyl" "cyl" "cyl" "cyl" "cyl"
# [3,] "disp" "disp" "disp" "disp" "disp" "disp" "disp"
# [4,] "carb" "am" "hp" "qsec" "am" "am" "am"
# [5,] "wt" "hp" "drat" "carb" "carb" "wt" "carb"
# [6,] "hp" "gear" "vs" "drat" "qsec" "gear" "qsec"
# [7,] "drat" "carb" "am" "vs" "wt" "vs" "hp"
# [8,] "qsec" "vs" "carb" "wt" "gear" "hp" "gear"
# [9,] "vs" "drat" "gear" "am" "drat" "drat" "drat"
# [10,] "am" "wt" "qsec" "gear" "vs" "qsec" "wt"
# [11,] "gear" "qsec" "wt" "hp" "hp" "carb" "vs"
我们可以看到每个 运行 的前三个列名称(此处显示为行)保持不变,而其他的则不同。