我正在尝试从类似于由以下代码创建的矩阵中进行采样:
set.seed(17)
x = sample(0:1, 100, replace=T)
x = matrix(x, 20)
xrowsum = apply(x, 1, sum)
x = x[xrowsum > 2, ]
x
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0 1 1 0 1
# [2,] 1 1 1 1 0
# [3,] 1 1 1 0 1
# [4,] 0 1 1 0 1
# [5,] 0 1 1 0 1
# [6,] 1 1 0 0 1
# [7,] 1 1 1 0 1
# [8,] 1 1 1 0 0
# [9,] 1 0 1 1 1
#[10,] 1 1 1 1 1
#[11,] 1 1 0 1 1
目标是从每行中抽取两个项目,但只有那些等于 1 的条目,并将 0 分配给该行的其余部分。一个预期的结果可能如下所示。
# [,1] [,2] [,3] [,4] [,5]
# [1,] 0 1 1 0 0
# [2,] 1 0 0 1 0
# [3,] 1 0 0 0 1
# [4,] 0 1 0 0 1
# [5,] 0 1 0 0 1
# [6,] 0 1 0 0 1
# [7,] 0 1 1 0 0
# [8,] 1 0 1 0 0
# [9,] 1 0 0 1 0
#[10,] 0 0 1 1 0
#[11,] 0 1 0 0 1