Store a variable directly from loading in r - r

I have an RData "E.g.RData"
I loaded it into R console using the load function.
load("E.g.RData")
it has a variable e.g. in RData.
I am doing like this -
e <- load("E.g.RData")
then e gets the character vector as "e.g."
but I want the contents of e.g. into e.
Is there a way to do it in R?

Yeah, the problem is that E.g maintains its name during the saving of the object. You could try assigning the new name "e" to the E.g. object and then remove the E.g. object:
E.g <- runif(100)
save(E.g, file="E.g.Rdata")
load("E.g.Rdata")
assign("e", E.g)
rm(E.g)

This can be done using:
y <- get(load("path/E.g.RData"))
y will contain the contents of the e.g. variable.

Rather than using the load function with its defaults, which overwrites anything of the same name in the global workspace, you may prefer to use attach to attach the workspace, then copy just the object(s) of interest with the names you want, then detach the workspace.

Related

How to save a function containing parameters into an RDS file?

Suppose that after some calculations I obtain a (floating) number, stored in the variable a, for example
a <- sqrt(2)
Now, I want to define a function that uses that parameter, for example:
myfunction <- function(x){x-a}
How can I save myfunction into an RDS file, in such a way that it can be loaded and used in a new R session, where the variable a is not defined?
Or from a different perspective: How to define the function, but substituting for a its actual numerical value in the function definition? That is, I'd like R to actually define the function
myfunction <- function(x){x - 2.1415.....}
where the actual value of a has been substituted in the definition.
Simply trying saveRDS(myfunction, 'myfunction.rds') does not work: if I start a new R session and do
myfunction <- readRDS('myfunction.rds')
myfunction(1)
then R complains that a is not defined.
Please note that I'm here giving a minimal working example of the problem. Obviously, in the case above I could just define myfunction <- function(x){x-sqrt(2)} and save that in an RDS file; it could be loaded in a new session and used without problems.
However, in my case I have many parameters like a, not just one, obtained from long calculations. I'm not interested in saving their values, I only want to save the function that uses them in its definition, and be able to use that function in a new R session.
An RDS file won't save the global environment, but if you create a closure, it will preserve the values in that environment. One such way to do what would be
myfunction <- {function(a) function(x){x-a}}(a)
And then you can call this function like a regular function
myfunction(1)

Can convert a string to an object but can't save() it -- why? [duplicate]

I am repeatedly applying a function to read and process a bunch of csv files. Each time it runs, the function creates a data frame (this.csv.data) and uses save() to write it to a .RData file with a unique name. Problem is, later when I read these .RData files using load(), the loaded variable names are not unique, because each one loads with the name this.csv.data....
I'd like to save them with unique tags so that they come out properly named when I load() them. I've created the following code to illustrate .
this.csv.data = list(data=c(1:9), unique_tag = "some_unique_tag")
assign(this.csv.data$unique_tag,this.csv.data$data)
# I want to save the data,
# with variable name of <unique_tag>,
# at a file named <unique_tag>.dat
saved_file_name <- paste(this.csv.data$unique_tag,"RData",sep=".")
save(get(this.csv.data$unique_tag), saved_file_name)
but the last line returns:
"Error in save(get(this_unique_tag), file = data_tag) :
object ‘get(this_unique_tag)’ not found"
even though the following returns the data just fine:
get(this.csv.data$unique_tag)
Just name the arguments you use. With your code the following works fine:
save(list = this.csv.data$unique_tag, file=saved_file_name)
My preference is to avoid the name in the RData file on load:
obj = local(get(load('myfile.RData')))
This way you can load various RData files and name the objects whatever you want, or store them in a list etc.
You really should use saveRDS/readRDS to serialize your objects.
save and load are for saving whole environments.
saveRDS(this.csv.data, saved_file_name)
# later
mydata <- readRDS(saved_file_name)
you can use
save.image("myfile.RData")
This worked for me:
env <- new.env()
env[[varname]] <- object_to_save
save(list=c(varname), envir=env, file='out.Rda')
You could probably do it without a new env (but I didn't try this):
.GlobalEnv[[varname]] <- object_to_save
save(list=c(varname), envir=.GlobalEnv, file='out.Rda')
You might even be able to remove the envir variable.

Modify the randomNames environment to add/remove names

The randomNames package in R can be used to generate random first and last names. There is an environment called randomNamesData that is loaded with the package and randomNamesData contains
> randomNamesData
<environment: 0x11db12078>
Similar output for str(randomNamesData) and dput(randomNamesData).
if you examine this randomNamesData with View you get the following:
> View(randomNamesData)
The objects in each of these objects (such as first_names_e1_g0) is of type array.
Is it possible to modify the randomNamesData environment to add more names? If it is possible, how to add/remove names to it?
I'm not clear on the exact changes you want to make, but since environments behave like lists, it should be possible to pull the data of interest into a temporary variable, modify that variable, and then replace the original:
tmp <- randomNamesData$first_names_e1_g0
[make changes to tmp]
randomNamesData$first_names_e1_g0 <- tmp

Best practice for naming archived objects?

I've got a function that has a list output. Every time I run it, I want to export the results with save. After a couple of runs I want to read the files in and compare the results. I do this, because I don't know how many tasks there will be, and maybe I'll use different computers to calculate each task. So how should I name the archived objects, so later I can read them all in?
My best guess would be to dynamically name the variables before saving, and keep track of the object names, but I've read everywhere that this is a big no-no.
So how should I approach this problem?
You might want to use the saveRDS and readRDS functions instead of save and load. The RDS version functions will save and read single objects without the attached name. You would create your object and save it to a file (using paste0 or sprintf to create unique names), then when processing the results you can read in one object at a time, or read several into a list to work with them.
You can use scope to hide the retrieved name inside a function, so first you might save a list to a file:
mybiglist <- list(fred=1, john='dum di dum', mary=3)
save(mybiglist, file='mybiglist1.RData')
Then you can load it back in through a function and give it whatever name you like be it inside another list or just a plain object:
# Use the fact that load returns the name of the object loaded
# and that scope will hide this object
myspecialload <- function(RD.fnam) {
return(eval(parse(text=load(RD.fnam))))
}
# now lets reload that file but put it in another object
mynewbiglist <- myspecialload('mybiglist1.RData')
mynewbiglist
$fred
[1] 1
$john
[1] "dum di dum"
$mary
[1] 3
Note that this is not really a generic 'use it anywhere' type function, as for an RData file with multiple objects it appears to return the last object saved... so best stick with one list object per file for now!
One time I was given several RData files, and they all had only one variable called x. In order to read all of them in my workspace, I loaded sequentially each the variable to its environment, and I used get() to read its value.
tenv <- new.env()
load("file_1.RData", envir = tenv)
ls(tenv) # x
myvar1 <- get(ls(tenv), tenv)
rm(tenv)
....
This code can be repeated for each file.

How to save() with a particular variable name

I am repeatedly applying a function to read and process a bunch of csv files. Each time it runs, the function creates a data frame (this.csv.data) and uses save() to write it to a .RData file with a unique name. Problem is, later when I read these .RData files using load(), the loaded variable names are not unique, because each one loads with the name this.csv.data....
I'd like to save them with unique tags so that they come out properly named when I load() them. I've created the following code to illustrate .
this.csv.data = list(data=c(1:9), unique_tag = "some_unique_tag")
assign(this.csv.data$unique_tag,this.csv.data$data)
# I want to save the data,
# with variable name of <unique_tag>,
# at a file named <unique_tag>.dat
saved_file_name <- paste(this.csv.data$unique_tag,"RData",sep=".")
save(get(this.csv.data$unique_tag), saved_file_name)
but the last line returns:
"Error in save(get(this_unique_tag), file = data_tag) :
object ‘get(this_unique_tag)’ not found"
even though the following returns the data just fine:
get(this.csv.data$unique_tag)
Just name the arguments you use. With your code the following works fine:
save(list = this.csv.data$unique_tag, file=saved_file_name)
My preference is to avoid the name in the RData file on load:
obj = local(get(load('myfile.RData')))
This way you can load various RData files and name the objects whatever you want, or store them in a list etc.
You really should use saveRDS/readRDS to serialize your objects.
save and load are for saving whole environments.
saveRDS(this.csv.data, saved_file_name)
# later
mydata <- readRDS(saved_file_name)
you can use
save.image("myfile.RData")
This worked for me:
env <- new.env()
env[[varname]] <- object_to_save
save(list=c(varname), envir=env, file='out.Rda')
You could probably do it without a new env (but I didn't try this):
.GlobalEnv[[varname]] <- object_to_save
save(list=c(varname), envir=.GlobalEnv, file='out.Rda')
You might even be able to remove the envir variable.

Resources