1

我有一个小矩阵,说

x <- matrix(1:10, nrow = 5) # values 1:10 across 5 rows and 2 columns

结果是

     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    3    8
[4,]    4    9
[5,]    5   10

我现在想要做的是在 x 中复制随机行;例如,生产

     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    5   10
[4,]    4    9 
[5,]    5   10

我相信 R 函数 'rep()' 是解决方案,也是 'sample()',但我不想在 sample() 中指定 size 参数;即,我希望每次都复制任意数量的行。

有没有使用 rep() 和 sample() 完成此任务的简单方法?

4

2 回答 2

2

我们可以使用该sample功能。我已经使用set.seed了可重复性,如果您删除该行,结果应该会改变。

set.seed(1848) # reproducibility
x[sample(x = nrow(x), size = nrow(x), replace = T), ]

     [,1] [,2]
[1,]    1    6
[2,]    2    7
[3,]    5   10
[4,]    1    6
[5,]    5   10
于 2018-02-27T19:11:29.617 回答
0

另一种选择可以作为 sample arow number 并将其替换为另一个 sampled row number。它将是:

x[sample(1:nrow(x),1),] <- x[sample(1:nrow(x),1),]


x
#     [,1] [,2]
#[1,]    5   10
#[2,]    2    7
#[3,]    3    8
#[4,]    4    9
#[5,]    5   10

或者

只是为了复制多达 3 个随机行,解决方案可能是:

x[sample(1:nrow(x),3),] <- x[sample(1:nrow(x),3),]
于 2018-02-27T19:27:02.520 回答