Pablo Boswell
Pablo Boswell

Reputation: 845

Rename global variables in R

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.

Upvotes: 0

Views: 2177

Answers (1)

Jthorpe
Jthorpe

Reputation: 10167

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)
    }
}

Upvotes: 2

Related Questions