在阅读了关于R方法的基准测试和速度比较之后,我正在转换为快速data.table
包,以便对我的大型数据集进行数据处理。
我遇到了一项特殊任务的问题:
对于某个观测变量,我想检查每个电台是否绝对滞后差(滞后1)是否大于某个阈值。如果是,我想用NA
替换它,否则什么都不做。
我可以使用data.table
命令为整个set
执行此操作,但我需要通过工作站执行此操作。
示例:
# Example data. Assume the columns are ordered by date.
set.seed(1)
DT <- data.table(station=sample.int(n=3, size=1e6, replace=TRUE),
wind=rgamma(n=1e6, shape=1.5, rate=1/10),
other=rnorm(n=1.6),
key="station")
# My attempt
max_rate <- 35
set(DT, i=which(c(NA, abs(diff(DT[['wind']]))) > max_rate),
j=which(names(DT)=='wind'), value=NA)
# The results
summary(DT)
我的实施问题是我需要通过电台进行此操作,而且我不希望得到电台1的最后一次读数和电台2的第一次读数之间的滞后差异。
我尝试在by=station
中使用[ ]
运算符,但我不知道如何执行此操作。
答案 0 :(得分:5)
一种方法是使用特殊变量.I
获取您要替换的行号,然后使用NA
运算符通过引用将:=
分配给这些行(或set
)。
# get the row numbers
idx = DT[, .I[which(c(NA, diff(wind)) > 35)], by=station][, V1]
# then assign by reference
DT[idx, wind := NA_real_]
This FR #2793当/如果实现将通过提供表达式来生成LHS上的相应索引和用RHS替换的值时,有更自然的方式来完成此任务。也就是说,在未来,我们应该能够做到:
# in the future - a more natural way of doing the same operation shown above.
DT[, wind[which(c(NA, diff(wind)) > 35)] := NA_real_, by=station]