Reputation: 1
I am having some trouble trying to figure this out.
I have a list of 3 dataframes:
list_of_dataframes = list(iris, trees, mtcars)
I need to use mapply
to return a list where:
the first element is the first column of the first dataframe of list_of_dataframe
the second element is the second column of the second dataframe of list_of_dataframe
the third element is the third column of the third dataframe of list_of_dataframe
Upvotes: 0
Views: 137
Reputation: 39154
We can also use the map2
function from the purrr
package to loop through the list of data frame (on the .x
argument) and the index of column 1:3
(on the .y
argument).
list_of_dataframes <- list(iris, trees, mtcars)
library(purrr)
map2(list_of_dataframes, 1:3, ~.x[, .y])
[[1]]
[1] 5.1 4.9 4.7 4.6 5.0 5.4 4.6 5.0 4.4 4.9 5.4 4.8 4.8 4.3 5.8 5.7 5.4 5.1 5.7 5.1
[21] 5.4 5.1 4.6 5.1 4.8 5.0 5.0 5.2 5.2 4.7 4.8 5.4 5.2 5.5 4.9 5.0 5.5 4.9 4.4 5.1
[41] 5.0 4.5 4.4 5.0 5.1 4.8 5.1 4.6 5.3 5.0 7.0 6.4 6.9 5.5 6.5 5.7 6.3 4.9 6.6 5.2
[61] 5.0 5.9 6.0 6.1 5.6 6.7 5.6 5.8 6.2 5.6 5.9 6.1 6.3 6.1 6.4 6.6 6.8 6.7 6.0 5.7
[81] 5.5 5.5 5.8 6.0 5.4 6.0 6.7 6.3 5.6 5.5 5.5 6.1 5.8 5.0 5.6 5.7 5.7 6.2 5.1 5.7
[101] 6.3 5.8 7.1 6.3 6.5 7.6 4.9 7.3 6.7 7.2 6.5 6.4 6.8 5.7 5.8 6.4 6.5 7.7 7.7 6.0
[121] 6.9 5.6 7.7 6.3 6.7 7.2 6.2 6.1 6.4 7.2 7.4 7.9 6.4 6.3 6.1 7.7 6.3 6.4 6.0 6.9
[141] 6.7 6.9 5.8 6.8 6.7 6.7 6.3 6.5 6.2 5.9
[[2]]
[1] 70 65 63 72 81 83 66 75 80 75 79 76 76 69 75 74 85 86 71 64 78 80 74 72 77 81 82
[28] 80 80 80 87
[[3]]
[1] 160.0 160.0 108.0 258.0 360.0 225.0 360.0 146.7 140.8 167.6 167.6 275.8 275.8
[14] 275.8 472.0 460.0 440.0 78.7 75.7 71.1 120.1 318.0 304.0 350.0 400.0 79.0
[27] 120.3 95.1 351.0 145.0 301.0 121.0
Upvotes: 2
Reputation: 99331
If you want atomic vectors returned, it would be
mapply("[", list_of_dataframe, 1:3)
But if you want single column data frames returned, you can do
Map("[", list_of_dataframe, 1:3)
or just use SIMPLIFY = FALSE
in mapply()
. And alternatively, you can use subset()
.
mapply(subset, list_of_dataframe, select = 1:3)
Upvotes: 2