我有一个很大的数据框列表,我想按特定年份过滤数据框中的列表。
DateAndTime 是包含 Y-M-D H:M:S 的列,我想仅按年份过滤数据框列表。
plot_list %>% lapply(dplyr::filter(plot_list, format(DateAndTime, "%Y") == year))
我尝试在列表中使用 lapply,但它似乎不起作用。任何帮助,将不胜感激。谢谢。
答案 0 :(得分:3)
如果我们在 plot_list
上循环,我们不需要在 plot_list
上再次使用 filter
。在 base R
中,这可以使用 subset
plot_list_sub <- lapply(plot_list, subset,
subset = format(DateAndTime, "%Y") == year)
或者使用lambda/anonymous
函数
plot_list_sub <- lapply(plot_list, function(x)
subset(x, format(DateAndTime, "%Y") == year))
或者如果我们想要 tidyverse
,用 list
循环 map
(来自 purrr
)并在 filter
元素上使用 list
.在这里,我们使用 lambda 函数 (~
),其中 .x
是该 list
library(dplyr)
library(purrr)
plot_list_sub <- map(plot_list, ~ .x %>%
filter(format(DateAndTime, "%Y") == year))