Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R rename an object / data.frame without intermediary object

I'm trying to rename a large R object (a data.frame ~ 9GB) to match up with some code that's already written. The object is saved with the name df1 and the code is written looking for an object named df2.

The only suggestion I've found here suggests creating a new, correctly named version of the object. This isn't an option given memory constraints. Is there a way to change the name of the object somewhere in the structure itself or maybe some kind of shallow copy? Any suggestions would be appreciated.

like image 692
screechOwl Avatar asked Aug 12 '14 18:08

screechOwl


2 Answers

@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
like image 118
Matthew Plourde Avatar answered Oct 16 '22 07:10

Matthew Plourde


When R makes a copy of an object it is initially only a "soft link" (i.e. the object is not actually copied but simply linked to another name). I suspect that removing the original instance would make the renaming operation permanent (i.e. remove the soft link and rename the object as initially intended). So memory consumption shouldn't increase upon such a renaming operation.

See:

  • How do I rename an R object?
like image 43
landroni Avatar answered Oct 16 '22 07:10

landroni