Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

r purrr problems using walk with save()

Tags:

r

save

purrr

I am looking for help using the purrr::walk function with save.

I have a list of four dfs that I want to write to four separate files. This is the code I used and the error I received. Both .x and ... are lists of the same length. I'm sure I'm making some simple error but not sure what that is. Thanks for the help.

# load libs
library(purrr)

# create dfs to loop over
df <- data.frame(
  a = rnorm(10),
  b = rnorm(10),
  c = rnorm(10),
  d = rnorm(10)
)
obj <- list(df1 = df, df2 = df, df3 = df, df4 = df )


# create file names to loop over
path <- "/user/home/"
folder <- "RDa/"
names <- c("df1", "df2", "df3", "df4")
fnames <- lapply(names, function(x) paste0(path, folder, x, ".RDa"))

# iterate
walk(obj, save, fnames)

Error in .f(.x[[i]], ...) : object ‘.x[[i]]’ not found

Session info

> sessionInfo()
R version 3.2.1 (2015-06-18)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
Running under: OS X 10.7.5 (Lion)

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] purrr_0.2.2

loaded via a namespace (and not attached):
[1] magrittr_1.5 tools_3.2.1  Rcpp_0.12.3  knitr_1.12.3
like image 377
jd24 Avatar asked Dec 25 '22 00:12

jd24


1 Answers

One way of doing this is to use walk2 and pass fnames in as the second parameter (.y) to the function (using ~ to define the function). So replace your last line with:

walk2(obj, fnames, ~ save(.x, file = .y))
like image 194
Nick F Avatar answered Jan 01 '23 20:01

Nick F