这是有关的现有问题的条件的数值,其中可以找到:替换由NA根据从其他列
Replace a numerical value by NA based on conditions from other columns:
下面是数据:
DT <- data.table(a = sample(c("C","M","Y","K"), 100, rep=TRUE),
b = sample(c("A","S"), 100, rep=TRUE),
f = round(rnorm(n=100, mean=.90, sd=.08),digits = 2)); DT
我想要对以下功能进行优雅和简洁的重写:
`%between%` <- function(x, vals) { x >= vals[1] & x <= vals[2]}
`%nbetween%` <- Negate(`%between%`)
和下面的脚本来替换满足一定的条件与NA
DT[a == "C" & b %in% c("A", "S") & f %nbetween% c(.85, .95), f := NA]
DT[a == "M" & b %in% c("A", "S") & f %nbetween% c(.85, .95), f := NA]
DT[a == "Y" & b %in% c("A", "S") & f %nbetween% c(.80, .90), f := NA]
DT[a == "K" & b %in% c("A", "S") & f %nbetween% c(.95, 1.10), f := NA]
那些看起来既优雅又对我简洁。也许你可以扩大你的问题,包括这是不是很好的enoguh?你可以在你的'data.table'和'J()'函数上使用'keys'来做你的子集以避免向量搜索。 – Justin
我跟着学校教了我什么,不要重新打字;写一个函数 –