How to loop and subset through a list of list

Viewed 40

I have a list where each element is a list. I want to create a sample for each element (train set) and return a new list.

For example, sim = [list1, list2, list3]

I am able to do it this way without a loop, but how would you optimize this?

trainID =sample(1:1000,700)
train1 <- sim[[1]][trainID,] #first list 
train2 <- sim[[2]][trainID,]
train3 <- sim[[3]][trainID,]
bigtrain <- list(train1, train2, train3)
3 Answers

Does this work?

bigtrain = list()
for(i in 1:3){
  bigtrain[[i]] <- sim[[i]][trainID,]
}

Use lapply :

bigtrain <- lapply(sim, function(x) x[trainID, ])

We can use tidyverse

library(dplyr)
library(purrr)
bigtrain <- map(sim, ~ .x %>% 
                          slice(trainID))
Related