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)
)
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With