简体   繁体   中英

Load .Rdata in User defined R package

I'm building my own R package and I have a reference data frame that needs to be accessed by the program. It's not very large and would require a user supplied string to search for the appropriate data.

Essentially, I have an .Rdata file with 1 data frame. I have stored the file in the /Rpackage_name/data/ directory of the package folder.

I would like for the package to load the data OR have access to its contents. This is what is confusing me.

What am I doing wrong?

GenericPackageName <- function () {
    #data("GenericPackageName")    did not work
}

If it is really not large, then put it in the code. Here is how to do it. Load the data into R, then use the sink() function to redirect the output to a file, and the dput() function to create the R code that creates the object. Assuming your data set is called iris , here is how to do it:

data(iris)
sink("/tmp/iris.R")
dput(iris)
sink(NULL)

system("cat /tmp/iris.R")

# structure(list(Sepal.Length = c(5.1, 4.9, 4.7, 4.6, 5, 5.4, 4.6, 
# 5, 4.4, 4.9, 5.4, 4.8, 4.8, 4.3, 5.8, 5.7, 5.4, 5.1, 5.7, 5.1, 
# ...
# 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 
# 3L), .Label = c("setosa", "versicolor", "virginica"), class = "factor")), .Names = c("Sepal.Length", 
# "Sepal.Width", "Petal.Length", "Petal.Width", "Species"), row.names = c(NA, 
# -150L), class = "data.frame")

Then just include this code in your package:

mydata <- structure(list(Sepal.length = ...

You can dump it into an R file and put that file in the R folder. When the package is added to the search list, the file will be sourced and the objects created.

Here's an example

## create some data in a fresh R session
> ls()
# character(0)
> d <- data.frame(x = 1:5, y = letters[1:5])
> save.image()
## load the data into R
> load(".RData", verbose = TRUE)
#Loading objects:
#  d
#  .Random.seed
## dump it into "newData.R" then source it
> dump("d", "newData.R")
> source("newData.R")
> ls()
# "d"

Here's a look at what dump does

> cat(readLines("newData.R"))
# d <- structure(list(x = 1:5, y = structure(1:5, .Label = c("a", "b",  
#     "c", "d", "e"), class = "factor")), .Names = c("x", "y"), 
#     row.names = c(NA,  -5L), class = "data.frame")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM