Calling/Passing 另一个变量的数据框

Calling/Passing a data frame by another variable

我正在尝试从 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"])

这是成功的。然而,它们是常量,需要随每个新符号进行更改。

如有任何帮助,我们将不胜感激。

当您想使用其字符值从工作环境中提取命名对象时,请尝试 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-对象已经处于可以使用的形式。)

我相当确定 XXX.Close 将始终是 getSymbols returns 对象中的第四列,因此如果您的对象是 X,那么 X[,4] 将为您提供所需的列。当然,单列对象还是会有类xtszoo,这样绘图等……就更方便了。如果你真的想要一个接近值的 numeric 向量,你可以使用 X[[4]] 删除 xtszoo 类。在下面的示例中,我创建了一个新环境 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

您可以使用 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