首先要知道为什么zoomChart() 返回你想要的值,而zooom() 没有。
zoomChart() 这样做是因为它调用了函数reChart(),该函数以invisible(chob) 行结束。 (chob 是您要查找的对象的名称。)
zooom() 不这样做。它调用zoomChart(),但它没有安排将chob 传递出正在评估zoomChart() 的环境。不过,您可以通过创建 zooom() 的修改版本来做到这一点
我首先将zooom 转储到一个文件中,然后创建一个名为zooom2 的编辑函数:
require(quantmod)
dump("zooom", file="zooom2.R")
我所做的三个修改是:
将对get.chob() 的调用替换为对quantmod:::get.chob() 的调用。这是必需的,因为与 zooom 不同,zooom2 没有 namespace:quantmod 作为其封闭环境。
将zoomChart()的输出赋值给对象chob。
以invisible(chob)结束函数,将chob返回到调用环境。
这是修改后的函数:
zooom2 <-
function (n = 1, eps = 2)
{
for (i in 1:n) {
cat("select left and right extremes by clicking the chart\n")
points <- locator(2)
if (abs(diff(points$x)) < eps) {
zoomChart()
}
else {
usr <- par("usr")
xdata <- quantmod:::get.chob()[[2]]@xdata
xsubset <- quantmod:::get.chob()[[2]]@xsubset
sq <- floor(seq(usr[1], usr[2], 1))
st <- which(floor(points$x[1]) == sq)/length(sq) *
NROW(xdata[xsubset])
en <- which(floor(points$x[2]) == sq)/length(sq) *
NROW(xdata[xsubset])
sorted <- sort(c(st, en))
st <- sorted[1]
en <- sorted[2] * 1.05
chob <- zoomChart(paste(index(xdata[xsubset])[max(1, floor(st),
na.rm = TRUE)], index(xdata[xsubset])[min(ceiling(en),
NROW(xdata[xsubset]), na.rm = TRUE)], sep = "::"))
}
}
cat("done\n")
invisible(chob)
}
您可以将函数获取或粘贴回您的 R 会话中,然后像这样使用它(例如):
data(sample_matrix)
chartSeries(sample_matrix)
d <- zooom2()
# Click to interactively zoom in
# extract the data visible in the selected region
d_sub <- d@xdata[d@xsubset,]
head(d_sub)
# Open High Low Close
# 2007-03-28 48.33090 48.53595 48.33090 48.53595
# 2007-03-29 48.59236 48.69988 48.57432 48.69988
# 2007-03-30 48.74562 49.00218 48.74562 48.93546
# 2007-03-31 48.95616 49.09728 48.95616 48.97490
# 2007-04-01 48.94407 48.97816 48.80962 48.87032
# 2007-04-02 48.90488 49.08400 48.90488 49.06316
如果这对您有用,您可能希望将其添加到 quantmod 源中,然后重新编译您自己的软件包版本。
希望这会有所帮助。