I think I have run into a very specific "idiosyncrasy" with purrr environmental variables that I do not understand.
GOAL: From a function, to call save
or saveRDS
of variables in the parent frame, given we know the variable names and can specify them in a character vector.
PROBLEM: When the function is inside purrr::map
, it doesn't work.
EXAMPLE:
fun <- function() {save(list = ".x", file = "/home/user/file.rdata")}
purrr::map(.x = list(iris), .f = ~fun())
error message in attached photo error message when nested in purrr
EXPECTED OUTPUT:
the function saves iris
to file
EDIT: i've also tried specifying every frame possible for save
. there is only one .x
but does not have the value of iris
.
I know I am getting the correct variable and I am in the correct environment, but it feels as though .x is "unevaluated" but get
doesn't work either. If anyone knows a way around this and why this behaviour exists that would be fantastic
you can use rlang::caller_env() but you almost certainly shouldnt. What follows is terrible, and there is almost certainly a better way to save your data out, but you get what you asked for ...
fun <- function(){
what_i_got <- get(".x",envir=rlang::caller_env())
# save it out or what have you
}
purrr::map(.x = list(iris), .f = ~fun())
what is normally done
fun <- function(.x){
what_i_got <-.x
# save it out or what have you
}
purrr::map(.x = list(iris), .f = fun)