Selectively sourcing scripts with map()?

Hi there,

I have a large analysis consisting of several different .R scripts. I'm interested in selecting a subset of these .R scripts and sourcing them to perform additional subanalyses. Sounds like it should be easy, but I've been banging my head against it and can't figure it out.

Here's my code:

CCCIscripts <- list.files(pattern = glob2rx("CCCI_*.R")) %>% as_vector()   # All CCCI analytic scripts
PwDscripts <- list.files(pattern = glob2rx("PwD*.R")) %>% as_vector()      # All PwD analytic scripts (interview data)
CGscripts <- list.files(pattern = glob2rx("CG*.R")) %>% as_vector()        # All CG analytic scripts (interview data)

analyticscripts <- c(CCCIscripts, PwDscripts, CGscripts) %>% 
  as_tibble() %>%   # Yeah this isn't kosher but yells at me
  filter(value %notin% c("CCCI_import_wrangle.R", "CCCI_timeline_15.R", "CCCI_fullanalysis.R", "CCCI_data_availability.R"))

str(analyticscripts) returns

Classes ‘tbl_df’, ‘tbl’ and 'data.frame':	11 obs. of  1 variable:
 $ value: chr  "CCCI_careplan.R" "CCCI_demographics.R" "CCCI_DME.R" "CCCI_ED.R" ...

So far, so good. But when I try map(analyticscripts$value, source(echo = TRUE)), I get the following error:

Error in source(echo = TRUE) : 
  argument "file" is missing, with no default

The "file" arguments should be the 11 filenames contained in value, so I'm not sure why source() isn't ingesting them. I'd appreciate any advice! If map() isn't the right way to go, can you please suggest an alternative? I've also tried sapply(analyticscripts, source(echo = TRUE)) and got the same error.

If worst comes to worst I can individually source these files but I'd like to do it the right way.

Thanks in advance!

purrr functions take formulas something like

 map(analyticscripts$value, ~source(., echo = TRUE))
1 Like

Thank you! :slight_smile: I don't know how I missed that!

This is also a good place to use purrr::walk instead of map, e.g.

walk(analyticscripts$value, source)

Yes - there's a master "setup" file I source first which defines %notin% as Negate(`%in%`). It's super helpful!

Oh this is great - thanks!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.