【发布时间】:2019-10-06 12:52:45
【问题描述】:
在 [xts1$master_decision] 中,我试图删除与上面一个单元格的值相同的行。我的目标是在不涉及任何其他包的情况下使用 R 基础来做到这一点。
如果有办法解决这个向量化,跳过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
【问题讨论】:
-
你不想从
zoo使用coredata吗? -
@Ronak。 [coredata] 很好用,因为它是上面代码中已经使用的 xts/zoo 的一部分。如果使用[coredata]分割索引和coredata,最终的结果还是需要xts格式。
标签: r for-loop vectorization xts