简体   繁体   中英

Apply filter function on list elements

I would like to subset my data (lists within a list) with the filter function, where I want to filter based on a list with selected dates. Applied for one single sublist, it works well, but the upscaling into a for loop for the whole data set causes problems either regarding the indexing or the automatically adding of the sublists to the main list (output is just the last sublist).

The filtering for one list element:


library(dplyr)
sublist_1 <- data.frame("value" = rnorm(10), "date" = 1:10, "parameter" = "X")
sublist_2 <- data.frame("value" = rnorm(10), "date" = 1:10, "parameter" = "Y"))
selected_dates_X <- c(3, 5, 7)
selected_dates_Y <- c(4, 6, 8)
df_total <-list("sublist_1" = sublist_1, "sublist_2" = sublist_2)


filtered_sublist_1 <- filter(df_total$sublist_2, 
                             date %in% selected_dates_Y)

My unsuccessful try to apply this in for loop, with an added if-statement. I want to create two lists, in which the filtered data is added for parameter X and Y, respectively.

df_X <- list()
df_Y <- list()

for (i in df_total) {
  if (i$parameter %in% "X") {
  filtered_sublist_X <- filter(df_total[[i]],
              date %in% selected_dates_X) 
  df_X[[length(df_X) + 1]] <- filtered_sublist_X
  
  } else {
    filtered_sublist_Y <- filter(df_total[[i]],
              date %in% selected_dates_Y) 
  df_Y[[length(df_Y) + 1]] <- filtered_sublist_Y
  }
}

As output, I want two datasets, filtered by selected_date for each parameter X and Y. Maybe this is not an appropriate approach to do this, then feel free to suggest other solutions, maybe with a function and lapply()? (Tried it, but also doesn't work)

Thanks!

You can try this lapply approach -

filtered_sublist_X <- lapply(df_total, function(x) 
            subset(x, parameter %in% "X" & date %in% selected_dates_X))

filtered_sublist_Y <- lapply(df_total, function(x) 
            subset(x, parameter %in% "Y" & date %in% selected_dates_Y))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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