1

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)
M--
  • 25,431
  • 8
  • 61
  • 93
maze
  • 335
  • 4
  • 9

2 Answers2

1

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.

Roman Luštrik
  • 69,533
  • 24
  • 154
  • 197
0

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)
Nick DiQuattro
  • 729
  • 4
  • 7