删除xts中重复的邻居值

时间:2019-05-20 07:22:52

标签: r for-loop vectorization xts

在[xts1 $ master_decision]中,我正在尝试删除值与上面一个单元格相同的行。我的目标是在不涉及任何其他软件包的情况下使用R base进行此操作。

如果有一种方法可以解决此向量化问题,则跳过for循环,这也很好。

# --------------------------------------
# Construct xts data.
# --------------------------------------

rows_to_build <- 6

dates <- seq(
  as.POSIXct("2019-01-01 09:01:00"),
  length.out = rows_to_build,
  by = "1 min",
  tz = "CEST"
  )

master_decision = c(
            # - Clarification what "for-loop" should do:
    3,      # Keep (missing [3] in cell above)
    2,      # Keep (missing [2] in cell above)
    2,      # Delete due to [2] in cell above)
    3,      # Keep (missing [3] in cell above)
    3,      # Delete due to [3] in cell above)
    2       # Keep (missing [2] in cell above)
)

data <- data.frame(master_decision)
xts1 <- xts(x = data, order.by = dates)


rm(list = ls()[! ls() %in% c("xts1")]) # Only keep [xts1].


# ------------------------------------------------------------
# For loop with purpose to remove duplicates that are grouped.
# ------------------------------------------------------------

for (i in 2:nrow(xts1)) {
    if(xts1[[i]] == xts1[[i-1]]) {
        xts1[-c(i)]
    }
}

xts1,然后再运行for循环:

                    master_decision
2019-01-01 09:01:00               3
2019-01-01 09:02:00               2
2019-01-01 09:03:00               2
2019-01-01 09:04:00               3
2019-01-01 09:05:00               3
2019-01-01 09:06:00               2

结果(带有时间戳[09:04:00]的行已删除:

                    master_decision
2019-01-01 09:01:00               3
2019-01-01 09:02:00               2
2019-01-01 09:03:00               2
2019-01-01 09:04:00               3
2019-01-01 09:06:00               2

想要的结果:(带有时间戳[09:04:00]和[09:05:00]的行已删除

2019-01-01 09:01:00               3
2019-01-01 09:02:00               2
2019-01-01 09:04:00               3
2019-01-01 09:06:00               2

2 个答案:

答案 0 :(得分:3)

这也可以完成这项工作。获取具有相同值的序列的第一个索引,并根据这些索引进行过滤。

idx <-cumsum(c(1,rle(master_decision)$lengths))
idx <- idx[-length(idx)]

xts1 <- xts(x = master_decision[idx], order.by = dates[idx])

2019-01-01 09:01:00    3
2019-01-01 09:02:00    2
2019-01-01 09:04:00    3
2019-01-01 09:06:00    2

答案 1 :(得分:2)

您可以使用coredata中的zoo,并通过设置数据来保留与先前值不同的值。

library(zoo)
xts1[c(TRUE, coredata(xts1)[-length(xts1)] != coredata(xts1)[-1]), ]

#                    master_decision
#2019-01-01 09:01:00               3
#2019-01-01 09:02:00               2
#2019-01-01 09:04:00               3
#2019-01-01 09:06:00               2

或者要将其完全保留在基数R中,请使用as.numeric

xts1[c(TRUE, as.numeric(xts1)[-length(xts1)] != as.numeric(xts1)[-1]), ]

另一种选择是使用head / tail而不是-length(xts1)-1进行子集

xts1[c(TRUE, tail(as.numeric(xts1), -1) != head(as.numeric(xts1), -1)), ]