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

后端 未结 3 879
予麋鹿
予麋鹿 2020-12-08 07:01

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 s

3条回答
  •  盖世英雄少女心
    2020-12-08 07:36

    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?

提交回复
热议问题