I've finally lost my habit of loops in R. Basically usually calculating new columns, and then doing calculations and aggregations on these new columns. But I have a question regarding cbind which I use for adding columns.
Is there a better way than using bind for things like this?
Naming this new column always is done by me in this tedious way... Anything cleverer/simpler out there?
library(quantmod)
getSymbols("^GSPC")
GSPC <- cbind(GSPC, lag(Cl(GSPC), k=1)) #Doing some new column calculation
names(GSPC)[length(GSPC[1,])] <- "Laged_1_Cl" #Naming this new column
GSPC <- cbind(GSPC, lag(Cl(GSPC), k=2))
names(GSPC)[length(GSPC[1,])] <- "Laged_2_Cl"
tail(GSPC)
** EDITED ** Roman Luštrik added a great solution in comments below.
GSPC$Laged_3_Cl <- lag(Cl(GSPC), k=3)
tail(GSPC)
One way of adding new variables to a data.frame is through the $
operator. Help page (?"$"
) shows common usage in the form of
x$i <- value
Where i
is the new variable name and value
are its associated values.