Create R data with a dynamic variable name from function for package?

岁酱吖の 提交于 2020-01-05 05:47:27

问题


I am working on a function which is part of a package. This package contains a template for a new package, and a function which creates R data for the new package which has to have a dynamic name provided to this function.

At the moment I am doing the following:

makedata <- function(schemeName, data) {
  rdsFile <- paste0(schemeName, ".rds")
  varName <- paste0(schemeName)
  saveRDS(
    data,
    file = file.path( ".", "data", rdsFile )
  )
  cat(
    paste0(varName, " <- readRDS(\"./", rdsFile, "\")"),
    file = file.path( ".", "data", paste0(varName, ".R") )
  )
}

makedata(name = "test", data = letters)

which results in two files in the data directory:

  1. a file test.rds containing letters but which is not loaded by R when the package is loaded (rds is not supported)

  2. a file test.R which has the code test <- readRDS("./test.rds") and which causes, when the package is loaded, the data in test.rds to be loaded in the variable test which than contains letters.

Now CRAN does not like rds files in the data directory.

Is there another way that I can use the standard formats (preferably RData) to achieve this?


回答1:


You can try something like this:

makedata <- function(schemeName, data) {
  rdataFile <- paste0(schemeName, ".rda")
  ## Assign data to the name saved in schemeName
  assign(x = schemeName, value = data)
  ## Save as RData file
  save(list = schemeName, file = file.path( ".", "data", rdataFile))
}



回答2:


A possible alternative with eval parse, as discussed in the comments.

makedata <- function(schemeName, data) {
  rdaFile <- paste0(schemeName, ".rda")
  fileLocation <- file.path( ".", "data", rdaFile )
  varName <- paste0(schemeName)

  assign(varName, data)
  eval(parse(text = sprintf("save(%s, file = '%s')", varName, fileLocation)))

  cat(sprintf("%s <- load(%s, file = '%s')", 
              varName, varName,
              fileLocation
              ),
      file = file.path( ".", "data", paste0(varName, ".R") ))
}

Off topic: Also, since you're developing packages, one convenient option might be using system.file instead of file.path due to option system.file('data/test.R', package = 'yourPackage') which allows to look in your package directory, wherever it is installed. Haven't tested your previous solution, it might be working fine too.



来源:https://stackoverflow.com/questions/56293910/create-r-data-with-a-dynamic-variable-name-from-function-for-package

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