将一个 xts 除以另一个 xts 并在此过程中创建一个新的 xts
Dividing one xts by another and creating a new xts in the process
我想将两个 xts 对象分开。每个 xts 具有相同的列数(具有相同的列名)但行数不同。我希望我的代码在其他 xts 中找到其各自的列并找到各自的日期值并将它们相除,然后将新输出放入具有相同列的新 xts。
例如:
xts 1
Date V1 V2
2017-07-21 4.5 NA
2017-09-15 NA 2.5
xts 2
Date V1 V2
2017-06-15 12.9 10.7
2017-07-21 6.7 2.2
2017-08-13 7.9 8.3
2017-09-15 4.5 3.2
新xts
Date V1 V2
2017-07-21 0.67 NA
2017-09-15 NA 1.28
这里是 apply
的解决方案:
> t(apply(xts1, 1, function(d)as.numeric(xts1[d[1],c('V1', 'V2')])/as.numeric(xts2[d[1],c('V1', 'V2')])))
[,1] [,2]
2017-07-21 0.6716418 NA
2017-09-15 NA 0.78125
我认为 xts
库实际上是一个非常了不起的工具,它会自动执行此操作
> xts1 <- structure(c(4.5, NA, NA, 2.5), .Dim = c(2L, 2L),
.Dimnames = list(NULL, c("V1", "V2")),
index = structure(c(1500595200, 1505433600), tzone = "UTC", tclass = "Date"),
class = c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date",
.indexTZ = "UTC", tzone = "UTC")
> xts2 <- structure(c(12.9, 6.7, 7.9, 4.5, 10.7, 2.2, 8.3, 3.2),
.Dim = c(4L, 2L), .Dimnames = list(NULL, c("V1", "V2")),
index = structure(c(1497484800, 1500595200, 1502582400, 1505433600),
tzone = "UTC", tclass = "Date"),
class = c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date",
.indexTZ = "UTC", tzone = "UTC")
> xts1 / xts2
V1 V2
2017-07-21 0.6716418 NA
2017-09-15 NA 0.78125
算术运算将尊重日期并在执行任何操作之前匹配它们。
希望对您有所帮助
我想将两个 xts 对象分开。每个 xts 具有相同的列数(具有相同的列名)但行数不同。我希望我的代码在其他 xts 中找到其各自的列并找到各自的日期值并将它们相除,然后将新输出放入具有相同列的新 xts。
例如:
xts 1
Date V1 V2
2017-07-21 4.5 NA
2017-09-15 NA 2.5
xts 2
Date V1 V2
2017-06-15 12.9 10.7
2017-07-21 6.7 2.2
2017-08-13 7.9 8.3
2017-09-15 4.5 3.2
新xts
Date V1 V2
2017-07-21 0.67 NA
2017-09-15 NA 1.28
这里是 apply
的解决方案:
> t(apply(xts1, 1, function(d)as.numeric(xts1[d[1],c('V1', 'V2')])/as.numeric(xts2[d[1],c('V1', 'V2')])))
[,1] [,2]
2017-07-21 0.6716418 NA
2017-09-15 NA 0.78125
我认为 xts
库实际上是一个非常了不起的工具,它会自动执行此操作
> xts1 <- structure(c(4.5, NA, NA, 2.5), .Dim = c(2L, 2L),
.Dimnames = list(NULL, c("V1", "V2")),
index = structure(c(1500595200, 1505433600), tzone = "UTC", tclass = "Date"),
class = c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date",
.indexTZ = "UTC", tzone = "UTC")
> xts2 <- structure(c(12.9, 6.7, 7.9, 4.5, 10.7, 2.2, 8.3, 3.2),
.Dim = c(4L, 2L), .Dimnames = list(NULL, c("V1", "V2")),
index = structure(c(1497484800, 1500595200, 1502582400, 1505433600),
tzone = "UTC", tclass = "Date"),
class = c("xts", "zoo"), .indexCLASS = "Date", tclass = "Date",
.indexTZ = "UTC", tzone = "UTC")
> xts1 / xts2
V1 V2
2017-07-21 0.6716418 NA
2017-09-15 NA 0.78125
算术运算将尊重日期并在执行任何操作之前匹配它们。
希望对您有所帮助