10

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.

Community
  • 1
  • 1
screechOwl
  • 27,310
  • 61
  • 158
  • 267
  • It doesn't appear you can alias a variable in R, but may I ask why you can't just find and replace `df2` with `df1` in whatever code that calls it? – user1477388 Aug 12 '14 at 18:22
  • @user1477388: That's my worst case scenario. I'm scared of blanket replaces. You never know what other fish you catch in that net... – screechOwl Aug 12 '14 at 18:23
  • As long as you aren't changing any data in the data frame, the first answer here should help: http://stackoverflow.com/questions/2717757/how-do-i-rename-an-r-object – Will Beason Aug 12 '14 at 18:31

2 Answers2

12

@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
Matthew Plourde
  • 43,932
  • 7
  • 96
  • 113
  • 2
    See also `pryr::object_size()` and the discussion in http://adv-r.had.co.nz/memory.html#object-size – hadley Aug 13 '14 at 12:42
11

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:

Community
  • 1
  • 1
landroni
  • 2,902
  • 1
  • 32
  • 39