如何打乱矩阵或数据帧中的值,使每个值在R中的每行/每列中只出现一次?
例如,以下是我所拥有的:
A, A, A, A
B, B, B, B
C, C, C, C
D, D, D, D
E, E, E, E
F, F, F, F
G, G, G, G
我想要什么:
A, B, C, D
B, C, D, E
C, D, E, F
D, E, F, G
E, F, G, A
F, G, A, B
G, A, B, C
我要么需要向上/向下移动列并将其包装以保持输入,要么通过某种混洗函数来完成,该函数以确保行不会重复的方式混洗列。
您可以尝试outer
+%%
来产生循环移位
v <- LETTERS[1:4]
out <- matrix(
v[outer(seq_along(v) - 1, seq_along(v) - 1, `+`) %% length(v) + 1],
nrow = length(v)
)
使得
> out
[,1] [,2] [,3] [,4]
[1,] "A" "B" "C" "D"
[2,] "B" "C" "D" "A"
[3,] "C" "D" "A" "B"
[4,] "D" "A" "B" "C"
更新如果你的矩阵不是正方形的,你可以尝试下面的代码
v <- LETTERS[1:7]
out <- t(
head(
matrix(
v[outer(seq_along(v) - 1, seq_along(v) - 1, `+`) %% length(v) + 1],
nrow = length(v)
), 4
)
)
它给出
> out
[,1] [,2] [,3] [,4]
[1,] "A" "B" "C" "D"
[2,] "B" "C" "D" "E"
[3,] "C" "D" "E" "F"
[4,] "D" "E" "F" "G"
[5,] "E" "F" "G" "A"
[6,] "F" "G" "A" "B"
[7,] "G" "A" "B" "C"