Is there an R function which removes an element of a list and stores all elements in another list

Viewed 52

I have 3 data sets in a list and I want to build a model using all combinations of test and training data. For example:

  • Model 1 : Train data - 1,2, Test data - 3
  • Model 2 : Train data - 1,3, Test data - 2
  • Model 3 : Train data - 2,3, Test data - 1

The approach I am using right now is laborious and not smart. Here is an example and my question is, how can I automate this procedure?

Day1 <- data.frame(x = c(1,2,3))
Day2 <- data.frame(x = c(4,5,6))
Day3 <- data.frame(x = c(7,8,9))

Days <- list(Day1,Day2,Day3)

Test <- list()
Train <- list()

Train[[1]] <- bind_rows(Day1, Day2)
Test[[1]] <- Day3
Train[[2]] <- bind_rows(Day1,Day3)
Test[[2]] <- Day2
Train[[3]] <- bind_rows(Day2,Day3)
Test[[3]] <- Day1
1 Answers

We can use combn to create all the combination of indices and then use lapply to select those elements for Train and remove those elements from Test.

train_inds <- combn(seq_along(Days), 2, simplify = FALSE)
Train <- lapply(train_inds, function(x) dplyr::bind_rows(Days[x]))
Test <- lapply(train_inds, function(x) dplyr::bind_rows(Days[-x]))

Check the output

Train
#[[1]]
#  x
#1 1
#2 2
#3 3
#4 4
#5 5
#6 6

#[[2]]
#  x
#1 1
#2 2
#3 3
#4 7
#5 8
#6 9

#[[3]]
#  x
#1 4
#2 5
#3 6
#4 7
#5 8
#6 9

Test
#[[1]]
#  x
#1 7
#2 8
#3 9

#[[2]]
#  x
#1 4
#2 5
#3 6

#[[3]]
#  x
#1 1
#2 2
#3 3
Related