Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use devtools::use_data on a list of data frames?

Tags:

r

devtools

I have a series of data frames that I want to save as individual .rda files in my package.

I could use devtools::use_data(my.df1, my.df2...) but I don't have a named object for each data frame, they are all stored in a big list.

What I would like is to do is to call use_data for each list element and use the list name for the .rda file name. But when I do the following, I have an error message:

> lapply(my.list, devtools::use_data, overwrite = TRUE)
Error: Can only save existing named objects

How can I do this?

like image 462
Ben Avatar asked Apr 05 '18 13:04

Ben


2 Answers

The use_data function seems to be very odd indeed requiring that an unquoted name is passed as a parameter that points to the object you want to save. This isn't conducive to working with objects in lists. But here is a possible solution with walk2 from purrr (though you could probably we-write with an mapply() if you want to use just base R)

library(purrr)
library(devtools)

walk2(my.list, names(my.list), function(obj, name) {
  assign(name, obj)
  do.call("use_data", list(as.name(name), overwrite = TRUE))
})
like image 50
MrFlick Avatar answered Nov 18 '22 17:11

MrFlick


You loop Assign(my.list, newNameOfYourList) over your list of lists. Then use devtools::use_data(newNameOfYourList, overwrite = TRUE).

like image 1
Charles Avatar answered Nov 18 '22 18:11

Charles