2

Is there a way in R to simply rename a data frame without first copying an existing data frame, giving it a new name, and then deleting the original?

I understand that the copied data frame does not take additional memory. I'm simply looking to limit the number of objects in my RStudio environment to reduce confusion and potential errors downstream.

For example:

df <- data_frame(a = c(1:5),
             b = c(6:10))

I know I can always do this

df2 <- df

# Or this
assign('df2', df)

But in both cases I still need to delete df, so I would rather do something like this:

df3 <- rename(df2) 
TClavelle
  • 578
  • 4
  • 12
  • Possible duplicate of [What exactly is copy-on-modify semantics in R, and where is the canonical source?](http://stackoverflow.com/questions/15759117/what-exactly-is-copy-on-modify-semantics-in-r-and-where-is-the-canonical-source) – zx8754 Jun 22 '16 at 21:03
  • something like this https://rhandbook.wordpress.com/tag/rename-data-frame/ – user5249203 Jun 22 '16 at 21:06
  • @zx8754 my objective is mainly to limit the number of objects in my environment without explicitly deleting the object with the original name. – TClavelle Jun 22 '16 at 22:39
  • Objective is clear, thanks. Would be nice to know why? – zx8754 Jun 22 '16 at 22:40
  • Mainly to avoid confusion when working with a lot of variables Rstudio and reduce the chances that naming errors break my code or make it harder to follow. – TClavelle Jun 22 '16 at 22:59
  • "a lot of variables" - use lists. "naming error" - use naming conventions. – zx8754 Jun 23 '16 at 06:31

1 Answers1

0

Are you concerned about creating a new object and storage issues? Because according to @Hadley's post in this thread http://r.789695.n4.nabble.com/renaming-objects-td851715.html, if you simply assign two objects the same value R doesn't actually create a new object. Following Hadley's example you can see that "R will only create a copy if a or b is modified":

   a <- data.frame(a = c(1:5),b = c(6:10))
 gc()
          used (Mb) gc trigger  (Mb) max used  (Mb)
Ncells 1661290 88.8    2564037 137.0  2403845 128.4
Vcells 2354971 18.0    7963162  60.8 63055235 481.1

 b <-a
 gc()
          used (Mb) gc trigger  (Mb) max used  (Mb)
Ncells 1661285 88.8    2564037 137.0  2403845 128.4
Vcells 2354961 18.0    7963162  60.8 63055235 481.1

One good way to conceptualize this might be thinking of a and b as just pointers to the same object in R. So the object is being stored only once, but can be referred to by both a and b.

Mike H.
  • 13,960
  • 2
  • 29
  • 39