xts - 返回缺失行的列表并计算缺失行的百分比

时间:2017-01-25 14:10:53

标签: r xts

是否有一种简单的方法可以返回xts中缺少的行列表?下面产生一个xts,对于这个例子,它故意缺少2行。

此外,当具有列表(缺失的行)时,是否可以计算缺失行的百分比(例如,缺少2行,其中总数应为100行= 2%或缺少行)。

# load dependent packages
library(xts)

# create a set of test data to be used
d <- as.POSIXct(c("2017/01/01 09:00:00", "2017/01/01 09:02:00",
              "2017/01/01 09:02:00", "2017/01/01 09:05:00"))
o = c(98.00, 97.67, 98.00, 98.10) # for "open" data
h = c(99.71, 98.97, 99.71, 99.41) # for "high" data
l = c(96.81, 96.86, 96.81, 97.70) # for "low" data
c = c(97.67, 98.67, 97.67, 98.83) # for "close" data
v = c(1000, 22000, 1000, 50000) # for "volume" data
a = c(1000, 22000, 1000, 50000) # for "adjusted" data

# create a dataframe
mydf1 <- data.frame("date" = d, "open" = o, "high" = h, "low" = l,
                "close" = c, "volume" = v, "adjusted" = a)

# create an xts based on dataframe mydf1
myxts1 <- xts(mydf1[,-1], order.by = mydf1$date)

1 个答案:

答案 0 :(得分:1)

这是该任务的提案。

根据xts对象中的当前时间计算包含所有时间的向量:

all_times <- seq(min(time(myxts1)), max(time(myxts1)),
                 by = min(diff(time(myxts1))))

创建包含缺失时间的向量:

missing_times <- all_times[!all_times %in% time(myxts1)]

missing_times
# [1] "2017-01-01 09:01:00 CET" "2017-01-01 09:04:00 CET"

失踪次数的百分比:

length(missing_times) / length(all_times) * 100
# [1] 33.33333