I am trying to extract the SPY.Close column from the data frame SPY which is created by quantmod. However, I would like to generalize this so that whatever symbol I pass initially can be used to create the close vector.
library(quantmod)
library(wmtsa)
library(ggplot2)
library(tseries)
library(pracma)
s <- getSymbols("SPY")
s <- as.name(s)
field <- c(paste(s,".Close",sep=""))
close <- as.vector(s[,field])
If I were to just type in
close <- as.vector(SPY[,"SPY.Close"])
this is successful. However they are constants and would need to be changed with every new symbol.
Any help would be appreciated.
When you want to pull a named object from the working envirnomnet using its character value then try get
:
s <- getSymbols("SPY")
field <- c(paste(s,".Close",sep=""))
close <- get(s)[, field]
str(get(s)[, field])
An ‘xts’ object on 2007-01-03/2015-01-27 containing:
Data: num [1:2031, 1] 141 142 141 141 141 ...
- attr(*, "dimnames")=List of 2
..$ : NULL
..$ : chr "SPY.Close"
Indexed by objects of class: [Date] TZ: UTC
xts Attributes:
List of 2
$ src : chr "yahoo"
$ updated: POSIXct[1:1], format: "2015-01-28 10:06:17"
(The as.name
was not needed and may have confused the matter at hand. The s
-object was already in a form that could be used.)