Home > OS >  How to use higher-order function (e.g. lapply or map) instead of for-loop to filter through a list o
How to use higher-order function (e.g. lapply or map) instead of for-loop to filter through a list o

Time:03-18

As the subject suggests, how can I write the following operation with lapply/map/etc to be more efficient in R?

for(i in 1:length(tbl)){
  tbl[[i]] <- filter(tbl[[i]], tbl[[i]][, 7] >= 10)
}

The idea is to basically filter the 7th column from each element (data frame) of the list so that the output only gives values that hold 10 or greater in the 7th column of all data frames. I tried something like this, but didn't get the code working:

lapply(tbl, function(x) filter(x, tbl[[x]][, 7] >= 10))

CodePudding user response:

lapply(tbl, function(x) x[x[,7] >= 10,])

or using dplyr::filter

lapply(tbl, function(x) filter(x, x[,7] >= 10))

using purrr::map

map(tbl, ~filter(.x, .x[,7] >= 10))
  • Related