1

I have some large sf objects that live in the Global Environment while the main code is executed. This main code calls create_foo_map functions that use filtered versions of the large sf objects and also import/create their own smaller sf objects to which the same filters should be applied. Ideally, the filter would work inside create_foo_map and leave the large objects in the global environment untouched.

This post on list2env led me to something like the following, which applies the same filter across various datasets but would need a lot of tweaking to work across two environments.

library(dplyr)
library(purrr)

set.seed(100)


volcano1 <- sample_frac(faithful, 0.25)
volcano2 <- sample_frac(faithful, 0.25)
volcano3 <- sample_frac(faithful, 0.25)
volcano4 <- sample_frac(faithful, 0.25)



exclude <- function(df) {

  df <- get(df)

  df %>% 
    filter(waiting > 90)

}


basic_obj <- ls(pattern = "volcano")

mod_obj <- map(basic_obj, exclude) 

names(mod_obj) <- basic_obj

list2env(mod_obj, envir = environment())
#> <environment: R_GlobalEnv>

So, I have two (sets of) questions:

1) Is this the simplest method to apply the same filter across several dataframes? I was thinking of purrr::modify but didn't end up with anything simpler.

2) Can this (or an alternative method) be expanded to dataframes both inside a function and in the global environment (or another env)? How?

Thanks in advance for any pointers!

Fons MA
  • 1,142
  • 1
  • 12
  • 21
  • 1
    To be honest I'm not quite sure what you're trying to do. I would keep all objects in a `list`, and then uniformly operate on these objects using `purrr::map`/`lapply`. Why do you need to do `list2env`? I would import all datasets and store resulting objects in a `list` directly, e.g. using something along the lines of `lst <- map(list_of_filenames, read_csv)`. – Maurits Evers Mar 21 '19 at 00:17
  • @Maurits thanks! I probably shouldn't have mentioned imports as that's not the point. I was trying to generalise from my specific example. I have some large SF objects that live in the Global Environment while the main code is executed. This main code calls map-making functions that use filtered versions of the large SF objects and also create their own smaller objects to which the same filters should be applied. – Fons MA Mar 21 '19 at 03:43

0 Answers0