在 sapply 内部使用 sapply

Using sapply inside sapply

我需要在另一个 sapply 中执行 sapply。

这是我的工作代码。

animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin", "Panda")
a <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(a) <- (animal)

我想在不执行此操作的情况下构建此数据框 10 次。

animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin", "Panda")

a <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(a) <- (animal)

b <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(b) <- (animal)

...

j <- as.data.frame(sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL))))
colnames(j) <- (animal)

我已经试过了,但没有成功

sapply(letters[1:10], function(z) as.data.frame(sapply(1:7, function(y) rbinom(300, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL)))), colnames(letters[1:10]) <- (animal))

谢谢

如果您需要使用两个 apply 类型的函数来执行此操作,您可以这样做:

此外,您在 animal 中有八只动物,但只制作了 7 列。所以我缩短了 animal.

在外循环上使用 lapply 将始终 return 一个列表,根据我的理解,这比 sapply 更整洁。

animal <- c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin")

lapply(1:10, function(x){
  a <- as.data.frame(
    sapply(1:7, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL)))
  )
  names(a) <- (animal)
  a
})

您使用的是sapply,所以不清楚您希望最终结果是矩阵还是列表。如果您想要一个矩阵作为输出,那么一种直接的方法是使用您现有的代码,但从扩展向量(动物 x 重复)开始。

animal.reps = sapply(c("Dog", "Cat", "Bird", "Fish", "Monkey", "Lion", "Dolphin", "Panda"), paste, letters[1:10], sep = ".")
a = sapply(animal.reps, function(y) rbinom(30, 1, sample(seq(.4, .9, by=.1), 1, prob = NULL)) )

这给出了一个 30x80 矩阵:

> dim(a)
[1] 30 80

> a[1:10, 1:10]
      Dog.a Dog.b Dog.c Dog.d Dog.e Dog.f Dog.g Dog.h Dog.i Dog.j
 [1,]     1     1     1     1     1     0     1     1     1     0
 [2,]     1     1     0     0     1     0     0     1     1     0
 [3,]     1     0     1     1     1     0     1     1     1     0
 [4,]     1     1     0     1     1     1     1     1     1     0
 [5,]     1     1     1     0     1     1     0     1     1     0
 [6,]     0     1     0     1     1     0     0     1     1     1
 [7,]     1     1     0     1     1     1     1     1     1     1
 [8,]     1     1     1     1     1     0     1     1     1     1
 [9,]     1     1     0     1     1     0     1     1     1     0
[10,]     0     1     1     1     1     1     1     1     1     1