Reputation: 1
So I have a list of length 9 where each element is a dataframe. I wanted to extract specific columns from each dataframe in the most efficient way possible, so I used the below function.
Down <- lapply(tables, "[", 2)
This successfully extracted the information I wanted, but why? What is "[" and how does it satisfy the semantics of lapply?
Upvotes: 0
Views: 59
Reputation: 2301
To augment Ritchie Sacramento's very nice explanation, you can also access the dataframe columns in a list using conventional notation:
cars1 <- mtcars
cars2 <- cars1
cars3 <- cars2
tables <- list(cars1, cars2, cars3)
lapply(tables, function(x) x$cyl)
[[1]]
[1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
[[2]]
[1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
[[3]]
[1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
lapply(tables, function(x) x[, 2])
[[1]]
[1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
[[2]]
[1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
[[3]]
[1] 6 6 4 6 8 6 8 4 4 6 6 8 8 8 8 8 8 4 4 4 4 8 8 8 8 4 4 4 8 6 8 4
Upvotes: 1