Search code examples
rsapply

Using sapply inside sapply


I need to execute sapply inside another sapply.

This is the working code I have.

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)

I would like to build this data frame 10 time without doing this.

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)

I have tried this without success

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))

Thanks


Solution

  • If you need to do this with two apply type functions, you can do something like this:

    Also you have Eight animals in animal and only making 7 columns. So I have shortened animal.

    Using lapply on the outer loop will always return a list, which makes it a bit neater than sapply from what I understand you are trying to do.

    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
    })