我有一个大列表,其中包含多个小标题的单个列表。我只想使用 purrr::map 选择相关列,但收到错误消息,指出 dplyr::select 不适用于列表。
如果我的列表一次只包含一个小标题,则 dplyr::select 命令可以工作,因为 select 函数会将格式识别为小标题。所以解决这个错误应该很容易,但我无法完全做到这一点。
我得到的错误是:
不处理列表select()
我该如何解决这个问题,因为应该可以编写类似的命令:
cleaned_lists <- map(lists,select,matches("string1|string2|string3|string4|string5"))
提前致谢!
如果是嵌套的
list
,我们需要一个内部的map
library(purrr)
library(dplyr)
cleaned_lists <- map(lists, map, select,
matches("string1|string2|string3|string4|string5"))
-可重现的示例
> lists <- list(list(mtcars, iris), list(mtcars, iris))
> map(lists, select, matches("Species|mpg"))
Error in `.f()`:
! `select()` doesn't handle lists.
Run `rlang::last_error()` to see where the error occurred.
> str(map(lists, map, select, matches("Species|mpg")))
List of 2
$ :List of 2
..$ :'data.frame': 32 obs. of 1 variable:
.. ..$ mpg: num [1:32] 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
..$ :'data.frame': 150 obs. of 1 variable:
.. ..$ Species: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...
$ :List of 2
..$ :'data.frame': 32 obs. of 1 variable:
.. ..$ mpg: num [1:32] 21 21 22.8 21.4 18.7 18.1 14.3 24.4 22.8 19.2 ...
..$ :'data.frame': 150 obs. of 1 variable:
.. ..$ Species: Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...