问题
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:
a file
test.rds
containingletters
but which is not loaded by R when the package is loaded (rds is not supported)a file
test.R
which has the codetest <- readRDS("./test.rds")
and which causes, when the package is loaded, the data intest.rds
to be loaded in the variabletest
which than containsletters
.
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