我需要在另一个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))谢谢
发布于 2019-05-30 14:13:15
如果您需要使用两个apply类型的函数来执行此操作,则可以执行以下操作:
此外,您在animal中有8个动物,并且只制作了7列。所以我缩短了animal。
在外部循环中使用lapply将始终返回一个列表,这使得它比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
})发布于 2020-05-18 01:46:18
您正在使用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 1https://stackoverflow.com/questions/56366535
复制相似问题