How to save R data object that has been created using assign()?

这一生的挚爱 提交于 2021-01-29 08:45:57

问题


I'm creating variables based on certain string combinations. Each variable would store some values. In this example, to make it simple, they store a numerical value. However, in actual problem, each would store a tibble.

I need to store each tibble as RData and they have to be created using unique combinations of the string.

The problem is when I use save() on this variable, it couldn't find it so the save would fail.


res <- 12345
sku = 'sku_a'
index = '1'
# create variable based on string combination
# assign variable value with res
assign(paste0(index,'_arima_',sku), res) 

# return the value of the created variable
get(paste0(index,'_arima_',sku))

# save created variable as RData
save(paste0(index,'_arima_',sku), file = paste0(index,'_arima_',sku,'.RData'))
Error in save(paste0(index, "_arima_", sku), file = paste0(index, "_arima_",  : 
  object ‘paste0(index, "_arima_", sku)’ not found

save(get(paste0(index,'_arima_',sku)), file = paste0(index,'_arima_',sku,'.RData'))
Error in save(get(paste0(index, "_arima_", sku)), file = paste0(index,  : 
  object ‘get(paste0(index, "_arima_", sku))’ not found

save(eval(paste0(index,'_arima_',sku)), file = paste0(index,'_arima_',sku,'.RData'))
Error in save(eval(paste0(index, "_arima_", sku)), file = paste0(index,  : 
  object ‘eval(paste0(index, "_arima_", sku))’ not found


回答1:


The first argument of save which is the ... operator is captured unevaluated, so it seems you can't put an expression here. One quick way round this if you have magrittr or dplyr loaded is to use the pipe, which will work:

paste0(index,'_arima_',sku) %>% save(file = paste0(index,'_arima_',sku,'.RData'))

Note though that an added complexity is that variable names shouldn't start with a digit in R. In your case, the variable can only be got from the console by '1_arima_sku_a' (i.e. it needs to be quoted)



来源:https://stackoverflow.com/questions/62574711/how-to-save-r-data-object-that-has-been-created-using-assign

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!