How to Rename a Variable in R Without Copying the Object

How to rename a variable in R without copying the object?

R is smart enough not to make a copy if the variable is the same, so just go ahead, reassign and rm() the original.

Example:

x <- 1:10
tracemem(x)
# [1] "<0000000017181EA8>"
y <- x
tracemem(y)
# [1] "<0000000017181EA8>"

As we can see both objects point to the same address. R makes a new copy in the memory if one of them is modified, i.e.: 2 objects are not identical anymore.

# Now change one of the vectors
y[2] <- 3
# tracemem[0x0000000017181ea8 -> 0x0000000017178c68]:
# tracemem[0x0000000017178c68 -> 0x0000000012ebe3b0]:
tracemem(x)
# [1] "<0000000017181EA8>"
tracemem(y)
# [1] "<0000000012EBE3B0>"

Related post: How do I rename an R object?

R rename an object / data.frame without intermediary object

@landroni answered the question. Here's an example showing that this is indeed how R works.

# copy an object to a new variable name, no change in memory usage
rm(list=ls())
gc()
memory.size()
# [1] 40.15
big.obj <- seq(1e7)
memory.size()
# [1] 78.34
big.obj.renamed <- big.obj
memory.size()
# [1] 78.34
rm(big.obj)
memory.size()
# [1] 78.34

# if the first variable is modified, however, you see the evidence of a hard copy
rm(list=ls())
gc()
memory.size()
# [1] 40.15
big.obj <- seq(1e7)
memory.size()
# [1] 78.34
big.obj.renamed <- big.obj
memory.size()
# [1] 78.34
big.obj[1] <- 2 # modifying the original forces hard copy
memory.size()
# [1] 192.8

Using an object to rename a variable in R

You can use {{new_name}}

new_name <- paste("New","Name")

as.data.frame(state.x77) %>%
rename({{new_name}}:=Population) %>%
head()

New Name Income Illiteracy Life Exp Murder HS Grad Frost Area
Alabama 3615 3624 2.1 69.05 15.1 41.3 20 50708
Alaska 365 6315 1.5 69.31 11.3 66.7 152 566432
Arizona 2212 4530 1.8 70.55 7.8 58.1 15 113417
Arkansas 2110 3378 1.9 70.66 10.1 39.9 65 51945
California 21198 5114 1.1 71.71 10.3 62.6 20 156361
Colorado 2541 4884 0.7 72.06 6.8 63.9 166 103766

Alternatively, you can do this

state = as.data.frame(state.x77)
colnames(state)[which(colnames(state)=="Population")] <- new_name
head(state)

New Name Income Illiteracy Life Exp Murder HS Grad Frost Area
Alabama 3615 3624 2.1 69.05 15.1 41.3 20 50708
Alaska 365 6315 1.5 69.31 11.3 66.7 152 566432
Arizona 2212 4530 1.8 70.55 7.8 58.1 15 113417
Arkansas 2110 3378 1.9 70.66 10.1 39.9 65 51945
California 21198 5114 1.1 71.71 10.3 62.6 20 156361
Colorado 2541 4884 0.7 72.06 6.8 63.9 166 103766

How do I rename an R object?

Renaming an object and the colnames within it is a two step process:

SPY <- GSPC # assign the object to the new name (creates a copy)
colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY)) # rename the column names

Otherwise, the getSymbols function allows you to not auto assign, in which case you could skip the first step (you will still need to rename the columns).

SPY <- getSymbols("^GSPC", auto.assign=FALSE)

Comment from @backlin

R employs so-called lazy evaluation. An effect of that is that when you "copy" SPY <- GSPC you do not actually allocate new space in the memory for SPY. R knows the objects are identical and only makes a new copy in the memory if one of them is modified (i.e. when they are no longer the identical, e.g. when you change the column names on the following line). So by doing

SPY <- GSPC
rm(GSPC)
colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY))

you never really copy GSPC but merely give it a new name (SPY) and then tell R to forget the first name (GSPC). When you then change the column names you do not need to create a new copy of SPY since GSPC no longer exists, meaning you have truly renamed the object without creating intermediate copies.

Rename objects in environment r

If you can’t assign them directly with the correct name, then the easiest is to replace the environment by a new one. If you absolutely need to preserve the environment (because it’s referenced elsewhere), you can replace its contents using the same trick:

objs = mget(ls(env), env)
rm(list = ls(env), envir = env)
list2env(setNames(objs, new_names), env)

The relevant part here is the last parameter to list2env: if you leave it off, this just creates a new environment. If you specify an existing environment, the names are added to that instead.

This code will leave hidden names (i.e. names starting with .) untouched — to change this, provide the all.names argument to ls, or use names.

r - Rename R object while save()-ing it

This proved to be a little trickier that I expected. I'll be interested to see what others come up with, and also what any objections to my solution may be.

saveit <- function(..., file) {
x <- list(...)
save(list=names(x), file=file, envir=list2env(x))
}

foo <- 1
saveit(bar=foo, file="hi.Rdata")

Renaming Objects in RStudio context sensitive within entire Project

RStudio IDE v1.0 includes a feature called "Rename in scope" that aims to do this:

This feature makes it easy to rename all instances of a variable. The
tool is context aware; changing m to m1 won’t change mtcars to
m1tcars.

RStudio Rename in Scope animated GIF

I cannot find documentation for the feature. The example from the animated GIF works though when I place the cursor on the first instance of d (the variable name to replace), and then select Code -> Rename in Scope. However, when I try the same steps but starting from the second instance, it does not work. So apparently you need to start from the place where the variable is assigned?

## Example from animated GIF
library(dplyr)
library(magrittr)
library(ggplot2)

d <- mtcars %>% ## Instance 1
filter(cyl > 4) %>%
select(hp, mpg)

ggplot(data = d, aes(x=hp, y=mpg)) + ## Instance 2
geom_point() +
geom_smooth()

In practice, there still seem to be bugs that prevent the feature from working. For instance, the example below does not work unless the header is removed.

## Header ####
example <- 1:10
example[1]


Related Topics



Leave a reply



Submit