Reputation: 845
I have a large list of dataframes, and I would like to filter the list in the dataframe by a specific year.
DateAndTime is a column that contains Y-M-D H:M:S, and I would like to filter the list of dataframes by only the year.
plot_list %>% lapply(dplyr::filter(plot_list, format(DateAndTime, "%Y") == year))
I have tried to use lapply on the list, but it doesn't appear to be working. Any help would be appreciated. Thank you.
Upvotes: 1
Views: 378
Reputation: 887098
If we are looping over plot_list
, we don't need the plot_list
again on filter
. In base R
, this can be done using subset
plot_list_sub <- lapply(plot_list, subset,
subset = format(DateAndTime, "%Y") == year)
Or using lambda/anonymous
function
plot_list_sub <- lapply(plot_list, function(x)
subset(x, format(DateAndTime, "%Y") == year))
Or if we want tidyverse
, loop over the list
with map
(from purrr
) and use filter
on the list
element. Here, we use a lambda function (~
) with .x
being the element in that list
library(dplyr)
library(purrr)
plot_list_sub <- map(plot_list, ~ .x %>%
filter(format(DateAndTime, "%Y") == year))
Upvotes: 3