Better way to cbind newly calculated column and quickly naming output

830 views Asked by At

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)
2

There are 2 answers

0
Roman Luštrik On BEST ANSWER

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.

0
Nick DiQuattro On

You can name the new column on the left side of the assignment like so:

exdat <- data.frame(lets = LETTERS[1:10],
                    nums = 1:10)

exdat$combo <- paste0(exdat$lets, exdat$nums)