我应该如何使用char变量对书面函数中的选定列进行过滤?
library("data.table")
data = data.table(val = c(NA, 1, 2, 3, 4, 5))
dataFun = function(dt, number) {
colname = paste0("value_", number)
dt = dt[, (colname) := val + number]
# the lines below do not work
dt[is.na(colname), colname] = 0
dt[colname < 3, colname] = 3
dt[colname > 5, colname] = 5
return(dt)
}
data = dataFun(data, 1)
最佳答案
我们可以在colname
中指定.SDcols
,也可以在转换为符号后eval
uate
dataFun <- function(dt, number) {
colname <- paste0("value_", number)
dt <- dt[, (colname) := val + number]
colnm <- as.name(colname)
dt[is.na(eval(colnm)), (colname) := 0
][eval(colnm) < 3, (colname) := 3
][eval(colnm) > 5, (colname) := 5][]
}
dataFun(data, 1)
# val value_1
#1: NA 3
#2: 1 3
#3: 2 3
#4: 3 4
#5: 4 5
#6: 5 5