我正在尝试为n
次尝试中的每一个绘制可变数量的样本。在此示例中,n = 8
是因为length(n.obs) == 8
。绘制完所有样本后,我想将它们合并为matrix
。
这是我的第一次尝试:
set.seed(1234)
n.obs <- c(2,1,2,2,2,2,2,2)
my.samples <- sapply(1:8, function(x) sample(1:4, size=n.obs[x], prob=c(0.1,0.2,0.3,0.4), replace=TRUE))
my.samples
此方法产生list
。
class(my.samples)
#[1] "list"
我使用以下命令确定输出matrix
中所需的列数:
max.len <- max(sapply(my.samples, length))
max.len
#[1] 2
可以使用以下方式创建输出matrix
:
corrected.list <- lapply(my.samples, function(x) {c(x, rep(NA, max.len - length(x)))})
output.matrix <- do.call(rbind, corrected.list)
output.matrix[is.na(output.matrix)] <- 0
output.matrix
# [,1] [,2]
#[1,] 4 3
#[2,] 3 0
#[3,] 3 2
#[4,] 3 4
#[5,] 4 3
#[6,] 3 3
#[7,] 3 4
#[8,] 1 4
上述方法似乎很有效,因为n.obs
包含多个值,并且element
中至少包含一个n.obs > 1
。但是,我希望代码足够灵活以处理以下每个n.obs
:
以上sapply
语句返回2 x 8 matrix
和以下n.obs
。
set.seed(1234)
n.obs <- c(2,2,2,2,2,2,2,2)
上面的sapply
语句返回带有下面的integer
的n.obs
。
set.seed(3333)
n.obs <- c(1,1,1,1,1,1,1,1)
上面的sapply
语句返回带有下面的list
的n.obs
。
n.obs <- c(0,0,0,0,0,0,0,0)
以下是上述三个n.obs
中每个期望的示例结果:
desired.output <- matrix(c(4, 3,
3, 3,
2, 3,
4, 4,
3, 3,
3, 3,
4, 1,
4, 2), ncol = 2, byrow = TRUE)
desired.output <- matrix(c(2,
3,
4,
2,
3,
4,
4,
1), ncol = 1, byrow = TRUE)
desired.output <- matrix(c(0,
0,
0,
0,
0,
0,
0,
0), ncol = 1, byrow = TRUE)
如何概括代码,以便无论使用什么matrix
作为输入,它总是返回具有八行的n.obs
?一种方法是使用一系列if
语句来处理有问题的情况,但我认为可能会有一个更简单,更有效的解决方案。]
我正在尝试为n次尝试中的每一次绘制可变数量的样本。在此示例中,n = 8,因为length(n.obs)==8。绘制完所有样本后,我想将它们组合成...
我们可以编写一个函数:
您可以在Vectorize
参数上使用sample
size=
函数。