I'm using the quantmod package to import financial series data from Yahoo.
library(quantmod) getSymbols("^GSPC") [1] "GSPC"
I'd like to change the name of object "GSPC" to "SPX". I've tried the rename function in the reshape package, but it only changes the variable names. The "GSPC" object has vectors GSPC.Open, GSPC.High, etc. I'd like my renaming of "GSPC" to "SPX" to also change GSPC.Open to SPX.Open and so on.
names() function in R Language is used to get or set the name of an Object. This function takes object i.e. vector, matrix or data frame as argument along with the value that is to be assigned as name to the object. The length of the value vector passed must be exactly equal to the length of the object to be named.
If you select option R, a panel is displayed to allow you to enter the new data set name. Type the new data set name and press Enter to rename, or enter the END command to cancel. Either action returns you to the previous panel.
rename() function in R Language is used to rename the column names of a data frame, based on the older names.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With