Problem with rlang curly-curly

I am trying to use map() to save a list of objects in compressed format files individually (as .rds files). The code first reads all the objects and memory, filters them to include only the types of objects of interest and stores the result as a list. The function then should go ahead and take the objects one at a time and save the results in rds format. But, I clearly have not understood the new article about the {{ syntax. The result I've put in the reprex is the latest attempt. Can someone directly help or send me to another resource (other than the rlang 0.4 post on the tidyverse site) that explains how to use curly-curly in a manner even I can understand. I'm trying to switch to a more functional approach in my research and help here will be greatly appreciated. The code is below.

library(tidyverse)
library(rlang)
#> 
#> Attaching package: 'rlang'
#> The following objects are masked from 'package:purrr':
#> 
#>     %@%, as_function, flatten, flatten_chr, flatten_dbl,
#>     flatten_int, flatten_lgl, flatten_raw, invoke, list_along,
#>     modify, prepend, splice

## Prepare the vector of object names
objs_fail <- enframe(objects(), name = NULL) %>% 
   filter(str_sub(value, 1,3) %in% c("dif", "fil", "met", "myD", "tss")) 
objs_fail <- as.list(objs_fail$value)
type <- "vfail"

## function to take the objects and store them into individual compressed files
save_the_files <- function(objs, type) {
   map({{objs}}, saveRDS(.data[[obj]], 
                         paste0("./cg_", type, "/", .data[[obj]], "_", type, ".rds")))
}

Created on 2019-07-14 by the reprex package (v0.3.0)

The function would be called by a call like

save_the_files(objs_fail, "vfail")

and the individual objects in the list would be strings like "diffAnn"

Thanks for the help.

Jim Hunter

Hello, curly-curly is a tool for interfacing with tidy eval functions. There are also tools for creating tidy eval functions (which it seems you're trying to do here), but these are rather advanced. I'd suggest reading adv-r to develop an understanding of NSE.

What you need to do is take ... inputs with ensyms(), use as_string() to convert these to character (as you used them as part of the file names), and then obtain the values of these objects with list(...).

Perhaps something like this (untested):

save_the_files <- function(..., type) {
  names <- map_chr(ensyms(...), as_string)
  objs <- list(...)

  map2(objs, names, ~ saveRDS(.x, paste0("./cg_", type, "/", .y, "_", type, ".rds")))
}
2 Likes

Many thanks, Lionel. I will try this out this afternoon and check out the adv-r material on the point.

Best,

James Hunter