[英]Randomizing rows in a matrix but keeping groups together in R
I am trying to randomize a rather large matrix by row, however I need to keep same numbers in a particular column together. 我正在尝试按行随机分配一个较大的矩阵,但是我需要将特定列中的相同数字保持在一起。
For example: 例如:
# Table A
Column A Column B
0.1 1
0.6 1
1.5 1
23 2
18 2
0.5 2
0.6 3
19 3
0.7 3
My goal is to randomize by group, in this example by Column B
. 我的目标是按组随机分组,在此示例中按
Column B
分组。 I have tried sample.int(nrow(x))
, which worked fine to randomize all of the matrix, but is there a way to do this by group? 我已经尝试了
sample.int(nrow(x))
,它可以很好地将所有矩阵随机化,但是有没有一种按组做到这一点的方法?
A very straightforward approach would be to use "data.table", like this: 一种非常简单的方法是使用“ data.table”,如下所示:
> library(data.table)
> as.data.table(mydf)[, .(Column_B = sample(Column_A)), by = Column_B]
Column_B Column_B
1: 1 0.6
2: 1 1.5
3: 1 0.1
4: 2 23.0
5: 2 18.0
6: 2 0.5
7: 3 0.6
8: 3 0.7
9: 3 19.0
Or, more generally: 或更笼统地说:
as.data.table(mydf)[, sample(.SD), by = Column_B]
Similarly, with "dplyr": 类似地,使用“ dplyr”:
library(dplyr)
mydf %>%
group_by(Column_B) %>%
mutate(Column_A = sample(Column_A))
Without conversion to data.frame/data.table and without external packages you could use ?ave
combined with ?sample
: 如果不转换为data.frame / data.table且没有外部包,则可以将
?ave
与?sample
结合使用:
mymat[ave(seq_along(mymat[, "Col_A"]), mymat[, "Col_B"], FUN = sample),]
sample data: 样本数据:
set.seed(123)
mymat <- cbind(Col_A = rnorm(9), Col_B = rep(1:3, each = 3))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.