How do I rename an R object?

前端 未结 1 1828
长情又很酷
长情又很酷 2020-12-05 00:57

I\'m using the quantmod package to import financial series data from Yahoo.

library(quantmod)
getSymbols(\"^GSPC\")
[1] \"GSPC\"

I\'d like

相关标签:
1条回答
  • 2020-12-05 01:21

    Renaming an object and the colnames within it is a two step process:

    SPY <- GSPC # assign the object to the new name (creates a copy)
    colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY)) # rename the column names
    

    Otherwise, the getSymbols function allows you to not auto assign, in which case you could skip the first step (you will still need to rename the columns).

    SPY <- getSymbols("^GSPC", auto.assign=FALSE)
    

    Comment from @backlin

    R employs so-called lazy evaluation. An effect of that is that when you "copy" SPY <- GSPC you do not actually allocate new space in the memory for SPY. R knows the objects are identical and only makes a new copy in the memory if one of them is modified (i.e. when they are no longer the identical, e.g. when you change the column names on the following line). So by doing

    SPY <- GSPC
    rm(GSPC)
    colnames(SPY) <- gsub("GSPC", "SPY", colnames(SPY))
    

    you never really copy GSPC but merely give it a new name (SPY) and then tell R to forget the first name (GSPC). When you then change the column names you do not need to create a new copy of SPY since GSPC no longer exists, meaning you have truly renamed the object without creating intermediate copies.

    0 讨论(0)
提交回复
热议问题