如何通过编程访问时间序列?变量调用SPY列的报错排查
问题:通过变量访问xts/zoo对象列时触发错误
直接执行SPY.Close <- SPY[, 4]可以正常提取SPY的Close列,但通过变量拼接列名后执行SPY[target]却报错。
报错代码及输出
报错代码
library(quantmod) tickers <- c("SPY") getSymbols(tickers, from = "2007-01-01") print(typeof(SPY[, 4])) print(class(SPY[, 4])) print(names(SPY)) SPY.Close <- SPY[, 4] print(typeof(SPY.Close)) print(class(SPY.Close)) wanted="Close" target=paste0("SPY",".",wanted) print(target) SPY[target] # 执行此行报错
错误输出
[1] "double" [1] "xts" "zoo" [1] "SPY.Open" "SPY.High" "SPY.Low" [4] "SPY.Close" "SPY.Volume" "SPY.Adjusted" [1] "double" [1] "xts" "zoo" [1] "SPY.Close" [1] "SPY.Close" Error in if (length(c(year, month, day, hour, min, sec)) == 6 && all(c(year, : missing value where TRUE/FALSE needed In addition: Warning messages: 1: In as_numeric(YYYY) : NAs introduced by coercion 2: In as_numeric(MM) : NAs introduced by coercion 3: In as_numeric(DD) : NAs introduced by coercion 4: In as_numeric(YYYY) : NAs introduced by coercion 5: In as_numeric(MM) : NAs introduced by coercion 6: In as_numeric(DD) : NAs introduced by coercion
原因分析
xts/zoo对象的索引规则与普通数据框不同:
- 单括号
[x]默认用于行索引(时间维度),R会尝试把传入的target解析为时间格式,而"SPY.Close"不是合法的时间字符串,因此触发强制转换NA的警告,进而导致if判断缺失TRUE/FALSE值的错误。 - 列索引必须使用**双括号
[, col]**格式,明确指定是按列查询。
解决方法
以下是几种简洁有效的解决方式:
方法1:使用双括号指定列索引
直接用[, target]或[[target]]进行列查询:
library(quantmod) tickers <- c("SPY") getSymbols(tickers, from = "2007-01-01") wanted <- "Close" target <- paste0("SPY", ".", wanted) SPY.Close <- SPY[, target] # 或 SPY[[target]] class(SPY.Close) # 输出:"xts" "zoo"
方法2:直接使用后缀列名(更简洁)
quantmod返回的xts对象支持直接用不带ticker前缀的列名查询,无需拼接完整列名:
wanted <- "Close" SPY.Close <- SPY[, wanted] class(SPY.Close)
方法3:通过列名匹配获取索引
如果需要先确认列的位置,可以用which()获取列索引后再查询:
target <- paste0("SPY", ".", "Close") col_idx <- which(names(SPY) == target) SPY.Close <- SPY[, col_idx] class(SPY.Close)
内容的提问来源于stack exchange,提问作者Ray Tayek
相关产品推荐
相关产品推荐

