Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
)
like image 831
bmacwilliams Avatar asked Sep 08 '25 17:09

bmacwilliams


2 Answers

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.

like image 91
asd-tm Avatar answered Sep 10 '25 12:09

asd-tm


With rrapply. This works for any structure of nested lists:

rrapply::rrapply(
  L,
  f = \(x) x[, 1],
  classes = "data.frame"
)

Structure of the output:

# List of 3
# $ :List of 3
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 1 2 3
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 1 2 3
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 1 2 3
# $ :List of 3
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 4 5 6
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 4 5 6
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 4 5 6
# $ :List of 3
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 7 8 9
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 7 8 9
# ..$ : tibble [3 × 1] (S3: tbl_df/tbl/data.frame)
# .. ..$ X1: int [1:3] 7 8 9
like image 25
Maël Avatar answered Sep 10 '25 14:09

Maël