Home > Net >  Reduce the number of functions with lapply
Reduce the number of functions with lapply

Time:08-11

The number of indexes in the object pass_buffer_listw[[1:11]] and analysis_sample_year[[1:11]] correspond to the years from 2007:1017. I classify them by wave and then I store the lits into a single object. Is there a way in which I can avoid to repeat 11 times and I can use a single function? Thanks in advance

data_2007 <- lapply(seq(length(pass_buffer_list_w[[1]])), function(x) analysis_sample_year[[1]][which(!is.na(over(SpatialPoints(data.frame(analysis_sample_year[[1]]$X_proj,analysis_sample_year[[1]]$Y_proj)), pass_buffer_list_w[[1]][[x]]))), ])
data_2008 <- lapply(seq(length(pass_buffer_list_w[[2]])), function(x) analysis_sample_year[[2]][which(!is.na(over(SpatialPoints(data.frame(analysis_sample_year[[2]]$X_proj,analysis_sample_year[[2]]$Y_proj)), pass_buffer_list_w[[2]][[x]]))), ])
...
data_2017 <- lapply(seq(length(pass_buffer_list_w[[11]])), function(x) analysis_sample_year[[11]][which(!is.na(over(SpatialPoints(data.frame(analysis_sample_year[[11]]$X_proj,analysis_sample_year[[11]]$Y_proj)), pass_buffer_list_w[[11]][[x]]))), ])
analysis_buf <- list(data_2007, data_2008, data_2009, data_2010, data_2011, data_2012, data_2013, data_2014, data_2015, data_2016, data_2017)

CodePudding user response:

You could use a nested lapply():

analysis_buf <- lapply(1:11, \(i) {
  lapply(seq(length(pass_buffer_list_w[[i]])), \(x) {
    analysis_sample_year[[i]][which(!is.na(over(SpatialPoints(data.frame(analysis_sample_year[[i]]$X_proj,analysis_sample_year[[i]]$Y_proj)), pass_buffer_list_w[[i]][[x]]))), ])
  }
})

Also as @Roland's comment, this might be a Map case:

analysis_buf <- Map(\(lst1, lst2) {
  lapply(seq(length(lst1)), \(x) lst2[which(!is.na(over(SpatialPoints(data.frame(lst2$X_proj, lst2$Y_proj)), lst1[[x]]))), ])
}, pass_buffer_list_w, analysis_sample_year)
  • Related