首页 > 解决方案 > R:从 xts 对象导出特定值类

问题描述

我有几个可以包含不同“值”类的 xts 输出对象。所有 xts 对象都包含值类datetime并且spot具有相同的长度。一些 xts 对象包含另一个值类par

例如,对于具有值的 xts 对象par:(值为:“datetime”、“spot”和“par”)

$datetime           $spot
2017-10-02 09:05:00 4.503936e-04
2017-10-02 09:10:00 4.799895e-04
2017-10-02 09:15:00 5.181447e-04
2017-10-02 09:20:00 5.734970e-04
2017-10-02 09:25:00 5.637900e-04
2017-10-02 09:30:00 4.684099e-04
2017-10-02 09:35:00 5.149570e-04
2017-10-02 09:40:00 5.459784e-04

$par
        sigma      sigma_mu       sigma_h       sigma_k           phi           rho           mu1           mu2      delta_c1 
 0.0001963601  0.1727417926  0.0070247195  1.2313740300  0.1940041110  0.2426273212  0.6050628200  0.1732629813  0.3489579734 
     delta_c2      delta_c3      delta_c4      delta_c5      delta_s1      delta_s2      delta_s3      delta_s4      delta_s5 
-1.5338494995  1.0146674063  0.8648589185  0.2488922309 -1.3362789351  1.1684672029  2.0240062847  0.2421184159 -0.4020884885

我想导出 和 的datetimespot
我使用以下方法将 xts 对象保存为 csv。

for (n in c("vol1", "vol2", "vol3", "vol4", "vol5", "vol6", "vol7", "vol8")) {
  v = get(n)
  myFile <- paste0("Vola_Est", "_", n, ".csv")
  write.zoo(as.xts(do.call(rbind, unname(v))), file=myFile, sep=",")
}

其中 vol{i} 是 xts 对象。这适用于那些不包含值类的对象par。我猜这是因为数据在 xts 对象中呈现方式的“结构性中断”。

在下面找到生成输入数据的示例代码

library("highfrequency")
library("xts")
library("forecast")

time_index <- seq(from = as.POSIXct("2012-05-15 00:00:00"), 
                  to = as.POSIXct("2012-06-03 23:59:00"), by = "min")
t <- 1:length(time_index)

set.seed(1234)
value <- ts(15 + 0.001*t + 10*sin(2*pi*t/(length(t)/5)) + rnorm(length(t)),  freq=length(time_index)/5)

sample_file <- xts(value, order.by = time_index)
plot(value)

vol1 <- spotvol(sample_file)

# Compare to stochastic periodicity

init = list(sigma = 0.03, sigma_mu = 0.005, sigma_h = 0.007,
            sigma_k = 0.06, phi = 0.194, rho = 0.986, mu = c(1.87,-0.42),
            delta_c = c(0.25, -0.05, -0.2, 0.13, 0.02), delta_s = c(-1.2,
                                                                    0.11, 0.26, -0.03, 0.08))

# next method will take around 110 iterations
vol2 <- spotvol(sample_file, method = "stochper", init = init, marketopen = "00:00:00", marketclose = "23:59:00", tz = "GMT")

for (n in c("vol1", "vol2")) {
  v = get(n)
  myFile <- paste0("Vola_Est", "_", n, ".csv")
  write.zoo(as.xts(do.call(rbind, unname(v))), file=myFile, sep=",")
}

标签: rcsvexportxtszoo

解决方案


找到了解决方案。没有认识到 xts 对象中的值类可以像数据框中的列一样被调用。

使用以下循环将特定内容从 xts 导出到 csv。

for (n in c("vol1", "vol2", "vol3", "vol4", "vol5", "vol6", "vol7", "vol8")) {
  v = get(n)
  extr <- v[j = 'spot']
  vola <- as.data.frame(extr)
  myfile <- paste("Vola_Est_1Min_",n,".csv", sep="")
  write.csv(vola, myfile)
}

推荐阅读