简体   繁体   English

如何使用mapply()提取列表中特定数据帧的特定列?

[英]How to use mapply() to extract a certain column of a certain data frame in a list?

I am having some trouble trying to figure this out. 我在尝试解决此问题时遇到了一些麻烦。

I have a list of 3 dataframes: 我列出了3个数据框:

list_of_dataframes = list(iris, trees, mtcars) 

I need to use mapply to return a list where: 我需要使用mapply返回以下列表:

  • the first element is the first column of the first dataframe of list_of_dataframe 第一个元素是list_of_dataframe的第一个数据框的第一列

  • the second element is the second column of the second dataframe of list_of_dataframe 第二个元素是list_of_dataframe的第二个数据框的第二列

  • the third element is the third column of the third dataframe of list_of_dataframe 第三个元素是list_of_dataframe的第三个数据框的第三列

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() . 或者只是在mapply()使用SIMPLIFY = FALSE And alternatively, you can use subset() . 或者,您可以使用subset()

mapply(subset, list_of_dataframe, select = 1:3)

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). 我们还可以使用purrr包中的map2函数在数据框列表(在.x参数上)和列1:3的索引(在.y参数上)之间循环。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM