将输出应用于矩阵

时间:2019-03-22 18:24:22

标签: r matrix apply

我希望将apply语句的输出加载到matrix中。问题在于apply输出list的各行中元素的数量各不相同。

我可以使用for-loop来实现自己想要的功能,但更愿意在基础R中做同样的事情而没有循环。

下面是一个示例,该示例返回带有for-loop的所需输出:

my.data <- read.table(text = '
     fruit  n.samples min.weight  max.weight
    apples         10         10          14
   oranges          3         15          20
     pears          0          5           9
  cherries          6          1           3
', header = TRUE, stringsAsFactors = FALSE)

my.weights <- matrix(0, ncol = max(my.data$n.samples), nrow = nrow(my.data))

set.seed(1234)

for(i in 1:nrow(my.data)) {

    if(my.data$n.samples[i] > 0) my.weights[i, 1:my.data$n.samples[i]] <-
        sample(my.data$min.weight[i]:my.data$max.weight[i], 
        my.data$n.samples[i], replace = TRUE)
}

my.weights
#     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9] [,10]
#[1,]   10   13   13   13   14   13   10   11   13    12
#[2,]   19   18   16    0    0    0    0    0    0     0
#[3,]    0    0    0    0    0    0    0    0    0     0
#[4,]    3    1    3    1    1    1    0    0    0     0

这是一条apply语句,返回所需的data。我根本无法弄清楚如何将这些data加载到matrix中。我怀疑我忽略了一个非常简单的东西,但是我不知道那是什么。

set.seed(1234)

apply(my.data, 1, function(x) sample(x[3]:x[4], x[2], replace = TRUE))

#[[1]]
#[1] 10 13 13 13 14 13 10 11 13 12
#
#[[2]]
#[1] 19 18 16
#
#[[3]]
#integer(0)
#
#[[4]]
#[1] 1 3 1 1 1 1

0 个答案:

没有答案