我正在尝试从quantmod创建的数据框SPY中提取SPY.Close列。但是,我想概括一下,以便我最初传递的任何符号都可用于创建近似向量。
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])
如果我只是输入
close <- as.vector(SPY[,"SPY.Close"])
这是成功的。但它们是常量,需要随每个新符号进行更改。
任何帮助都将不胜感激。
答案 0 :(得分:1)
如果要使用其字符值从工作环境中提取命名对象,请尝试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"
(as.name
不需要,可能会混淆手头的问题。s
- 对象已经是可以使用的形式了。)
答案 1 :(得分:1)
我相当确定XXX.Close
将始终是getSymbols
返回的对象中的第四列,因此如果您的对象是X
,那么X[,4]
会给你想要的专栏。当然,单列对象仍将具有类xts
和zoo
,这将使绘图等更方便。如果您确实需要numeric
近似值向量,则可以使用X[[4]]
删除xts
和zoo
类。在下面的示例中,我创建了一个新的环境qm_env
来存储对象,这样他们就不会弄乱我的.GlobalEnv
- 您可以忽略我的表达式的with(qm_env, ...)
部分专注于...
:
library(quantmod)
##
qm_env <- new.env()
tickers <- c("SPY","MSFT","MMM")
##
sapply(tickers, function(x){
getSymbols(x,env=qm_env)
})
##
with(qm_env,close <- MMM[,4])
R> with(qm_env, head( close ))
MMM.Close
2007-01-03 78.26
2007-01-04 77.95
2007-01-05 77.42
2007-01-08 77.59
2007-01-09 77.68
2007-01-10 77.85
如果由于某种原因你不确定第四列将永远是接近的值,那么只需创建一个这样的函数
getClose <- function(x) {
x[,agrep("Close",names(x))]
}
应该做的工作:
R> with(qm_env, head( getClose(MSFT) ))
MSFT.Close
2007-01-03 29.86
2007-01-04 29.81
2007-01-05 29.64
2007-01-08 29.93
2007-01-09 29.96
2007-01-10 29.66
R> with(qm_env, head( getClose(SPY) ))
SPY.Close
2007-01-03 141.37
2007-01-04 141.67
2007-01-05 140.54
2007-01-08 141.19
2007-01-09 141.07
2007-01-10 141.54
答案 2 :(得分:1)
您可以使用quantmod::getPrice
,默认情况下会查找"*.Close"
列。
require(quantmod)
x <- getSymbols("SPY", auto.assign=FALSE)
head(getPrice(x))
# SPY.Close
# 2007-01-03 141.37
# 2007-01-04 141.67
# 2007-01-05 140.54
# 2007-01-08 141.19
# 2007-01-09 141.07
# 2007-01-10 141.54