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
Related
Sometimes data files come in .rdata objects. These are annoying compared to .rds files because the objects have predefined names. In my case, I want to rename the object automatically and get rid of the wrongly named version. Simple somewhat contrived example:
#make a new iris with a bad name
badnameiris = iris
#save it to a file
save(badnameiris, file = "iris.rdata")
#rename badname version from global envir
rm(badnameiris)
#read iris from file
irisname = load("iris.rdata")
#this variable is not iris, but the name of the variable it was assigned to
irisname
[1] "badnameiris"
#it's to use the right name with get()
goodnameiris = get(irisname)
#but harder to get rid of the wrong one with rm()
rm(irisname)
The last line does not work as intended because it requires a bare name as input and it gets a character vector. I realize one can actually use the list argument in rm(), but suppose one could not.
How does one in general convert from character to unquoted for these purposes?
I tried the rlang functions, but these are for non-standard evaluation as used in tidyverse context. I tried as.name(), as suggested here. Does not work either. Most questions I could find asking this question relate to tidyverse, but I'm trying to do base R context.
(An alternative solution above is to make a function that utilizes the destruction of the local environment to remove the unwanted copy of the object.)
Just use do.call:
x <- 1
s <- "x"
do.call(rm, list(s))
ls()
#[1] "s"
Or compute on the language:
eval(bquote(rm(.(s))))
I am trying to rename global variables with a for loop.
I do not have a reproducible example because this question relates to something very broad.
The first issue is that I am dealing with such large data sets that I must use data.tables. I want to rename (with a for loop) all data.tables in my global environment.
The first problem is how do I rename global environment variables.
Second, how do I rename global variables of a certain class type?
Mind, I want to do this in a for loop so that it can rename lists of variable length.
R does not have the concept of re-naming, but you can bind an object to a new
name and remove the old name. Since data.table objects use references, this
won't result in copying the underlying data, the way other assignments would.
# get the names of the variables in the global environment
globalVariables <- ls(envir=.GlobalEnv)
for(.name in globalVariables){
x <- get(.name,envir=.GlobalEnv)
if(inherits(x,'data.table')){
# obviously you want a better newName than 'foo'
newName <- 'foo'
# bind the value x to the new name in the global environment
assign(newName,x,envir=.GlobalEnv)
# delete the binding to the old name in the global environment
rm(list=.name,envir=.GlobalEnv)
}
}
I want to initialise some variables from an external data file. One way is to set a file like the following foo.csv:
var1,var2,var3
value1,value2,value3
Then issue:
attach(read.csv('foo.csv'))
The problem is that in this way var1, var2, var3 are not shown by ls() and most of all rm(all=ls()) doesn't clean all anymore and var1, var2, var3 are still there.
As the default position for new objects is '2', I can remove the workspace where this variables live via:
detach(pos=2)
or simply
detach()
Since pos=2 is the default for detach too.
But detach() is "too" powerful and it can delete R objects loaded by default. This means that, if one attaches many datasets, removing them with repeated detach can lead to delete also default R objects and you have to restart it. Besides the simplicity of the single rm(all=ls()) goes away.
One solution will be to attach var1, var2, var3 straight to the the global environment.
Do you know how to do that?
attach(read.csv('foo.csv'), pos=1)
issues a warning (future error).
attach(read.csv('foo.csv'), pos=-1)
seems ineffective.
If you want to read the variables straight into the global environment, you can do this:
{
foo<-read.csv('foo.csv')
for(n in names(foo)) assign(n,foo[[n]],globalenv())
}
The braces will prevent foo from also being added to the global environment. You can also make this into a function if you want.
Use the named variant of attach and detach:
attach(read.csv(text='var1,var2,var3\nvalue1,value2,value3'),
name = 'some_name')
and
detach('some_name')
This will prevent mistakes. You’d obviously wrap these two into functions and generate the names automatically in an appropriate manner (the easiest being via a monotonically increasing counter).
What about a 'safer' attach?
attach<-function(x) {for(n in names(x)) assign(n,x[[n]],globalenv()); names(x)}
'Safer' means you can see attached vars with ls() and most of all remove them with a single rm(list=ls())
Inspired by mrip
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.
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.