Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

I have a huge data frame loaded in global environment in R named df. How can I rename the data frame without copying the data frame by assigning it to another symbol and remove the original one?

like image 760
Kun Ren Avatar asked Apr 09 '14 02:04

Kun Ren


People also ask

How do I rename a data variable in R?

I'll just say it once more: if you need to rename variables in R, just use the rename() function.

How do I change a variable name in R studio?

It is achieved by selecting the function or variable we want to change and pressing Ctrl + Shift + Alt + M. It will select all occurrences in scope, you will have to just type a new name.

What does rename () do in R?

rename() function in R Language is used to rename the column names of a data frame, based on the older names.

How do you change a variable value in R?

The mutate() function is used to modify a variable or recreate a new variable. Variable are changed by using the name of variable as a parameter and the parameter value is set to the new variable.


2 Answers

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?

like image 111
evolvedmicrobe Avatar answered Sep 24 '22 09:09

evolvedmicrobe


There is a function called mv in the gdata package.

library(gdata)  x <- data.frame(A = 1:100, B = 101:200, C = 201:300)  tracemem(x) "<0000000024EA66F8>"  mv(from = "x", to = "y")  tracemem(y) "<0000000024EA66F8>" 

You will notice that the output from tracemem is identical for x and y. Looking at the code of mv, you will see that it assigns the object to the environment in scope and then removes the old object. This is quite similar to the approach C8H10N4O2 used (although mv is for a single object), but at least the function is convenient to use.

like image 29
panman Avatar answered Sep 20 '22 09:09

panman