rlistselectnested-lists

Extracting single data frame column from nested list


I have a nested list where the lowest level contains a data frame with multiple columns. Example below. I would like to extract from this a new list which contains only the first column of the data frame, "X1" in the example below, maintaining the rest of the list structure.

d1 <- tibble(X1 = 1:3, X2 = 0)
d2 <- tibble(X1 = 4:6, X2 = 0)
d3 <- tibble(X1 = 7:9, X2 = 0)

L <- list(
  list(d1, d1, d1),
  list(d2, d2, d2),
  list(d3, d3, d3)
)

Solution

  • I would offer:

    lapply(L, function(x) {
      lapply(x, function(x) x$X1) 
    })
    

    May I also give an advice not to use L for variable names as L is reserved for integer declaration in comparison to numeric. For instance 7L.