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?

- 4,715
- 3
- 35
- 50
-
1See [this](http://stackoverflow.com/a/2717853/489704) related answer and its comments. – jbaums Apr 09 '14 at 02:45
-
1You can also read [**this thread**](https://stat.ethz.ch/pipermail/r-help/2008-March/156028.html). – A5C1D2H2I1M1N2O1R2T1 Apr 09 '14 at 02:53
3 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?

- 1
- 1

- 2,672
- 2
- 22
- 30
-
15+1, but I think you could reinforce this answer with some "proof" (even with using something as simple as `x <- 1:10; tracemem(x); y <- x; tracemem(y); rm(x)`. – A5C1D2H2I1M1N2O1R2T1 Apr 09 '14 at 02:51
-
1good point, and that is a nice way to show the lazy evaluation. – evolvedmicrobe Apr 09 '14 at 03:22
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.

- 1,179
- 1
- 13
- 33
To apply the accepted answer to many objects, you could use a loop of assign(new_name, get(old_name))
followed by rm(list= old_names)
. For example, if you wanted to replace old_df
,old_x
,old_y
, ... with new_df
, new_x
...
for (obj_old_name in ls(pattern='old_')){
assign(sub('old_','new_',obj_old_name), get(obj_old_name))
}
rm(list=ls(pattern='old_'))

- 18,312
- 8
- 98
- 134