输出对象因输入数据而异

问题描述 投票:0回答:2

我正在尝试为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语句返回带有下面的integern.obs

set.seed(3333)
n.obs <- c(1,1,1,1,1,1,1,1)

上面的sapply语句返回带有下面的listn.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。绘制完所有样本后,我想将它们组合成...

r sapply
2个回答
2
投票

我们可以编写一个函数:


0
投票

您可以在Vectorize参数上使用sample size=函数。

© www.soinside.com 2019 - 2024. All rights reserved.