I have a data.frame in the following directory "/..../1_5_setpoint.Rdata".
The name of the data frame is "setpoint" and the name of the file is "1_5_setpoint". I want to create a data.frame with the name "1_5_setpoint". This is my code:
assign("1_5_setpoint", get(load("/..../1_5_setpoint.Rdata")))
The problem is that I end up having to data frames in memory: one called "setpoints" (I don't want this one) and one called "1_5_setpoint" (I want this one).
This could cause a problem if the data is very big.
Any suggestions?
It would be easier if you would save your data as RDS
not Rdata
, you could then simply load it to an object with a desired name:
saveRDS(mtcars, "mtcars.rds")
cars <- readRDS("mtcars.rds")
Rdata
files are used to store all objects you created, have a look at this explanation . As discussed here RDS
is batter solution for storing single objects.
@Konrad is correct about RDS being the right solution. Sometimes, you don't have the option of getting an RDS file and you only get a .RData file. In that case, the simplest method I know of is to load the data using a function and either return the only variable within or allow selection of the variable to return.
An example there could be:
myLoad <- function(filename, variable) {
tmp.env <- new.env()
varnames <- load(filename, envir=tmp.env)
if (missing(variable)) {
## Choose the variable name as the only variable in the file or
## give an error.
if (length(varnames) == 1) {
return(get(varnames, envir=tmp.env))
} else {
stop("More than one variable present in the file, please specify which variable to extract. Choices are: ",
paste(varnames, sep=", "))
}
} else {
return(get(variable, envir=tmp.env))
}
}
ls()
save(mtcars, file="mtcars.RData")
mtcars_1_5 <- myLoad("mtcars.RData")
identical(mtcars, mtcars_1_5)
ls()
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.