How would I access an xts column by name in a function? The code below returns NULL.
#m(list=ls())
#dev.off(dev.list()["RStudioGD"])
getSymbols("^GSPC",src="yahoo",from="2015-01-01",to = "2020-06-04")
str(GSPC)
frog<-function(ts,name) {
ts$name
}
frog(GSPC,"GSPC.Close")
quantmod provides Cl
and Ad
functions to extract the close and adjusted close. See ?Cl
for these and other extraction functions. For example, here are ways to get the close. Note that in the second one the portion after the $ must be the column name and not a variable holding the column name. Lists and data.frames work the same way with $ in R.
Cl(GSPC)
GSPC$GSPC.Close
GSPC[, "GSPC.Close"]
col <- "GSPC.Close"; GSPC[, col]
GSPC[, 4] # close is 4th column
frog <- function(x, col) if (is.function(col)) col(x) else x[, col]
frog(GSPC, Cl)
frog(GSPC, "GSPC.Close")
frog(GSPC, 4)