当变量名存储在字符向量中时,选择/赋值到data.table如何引用data.table如果变量名存储在字符向量中?例如,这适用于data.frame:df <- data.frame(col1 = 1:3)colname <- "col1"df[colname] <- 4:6df# col1# 1 4# 2 5# 3 6如何对data.table执行相同的操作?:=符号?最明显的是dt[ , list(colname)]不起作用(我也没料到)。
3 回答
万千封印
TA贡献1891条经验 获得超3个赞
with = FALSE
:DT = data.table(col1 = 1:3)colname = "col1"DT[, colname, with = FALSE] # col1# 1: 1# 2: 2# 3: 3
“点”( ..
)前缀: DT[, ..colname] # col1# 1: 1# 2: 2# 3: 3
..
:=
DT[, (colname) := 4:6] # col1# 1: 4# 2: 5# 3: 6
i
(colname)
使用 with = FALSE
带着 :=
现在所有情况下都不推荐使用,因为将lhs包装在 :=
使用括号已经有一段时间了。 colVar = "col1"DT[, colVar := 1, with = FALSE] # deprecated, still works silentlyDT[, (colVar) := 1] # please change to thisDT[, c("col1", "col2") := 1] # no changeDT[, 2:4 := 1] # no changeDT[, c("col1","col2") := list(sum(a), mean(b)] # no changeDT[, `:=`(...), by = ...] # no change
?`:=`
:
DT[i, (colnamevector) := value]# [...] The parens are enough to stop the LHS being a symbol
DT[, colname := cumsum(get(colname)), with = FALSE]# col1# 1: 4# 2: 9# 3: 15
eval
a paste
expr = paste0("DT[,",colname,":=cumsum(",colname,")]")expr# [1] "DT[,col1:=cumsum(col1)]"eval(parse(text=expr))# col1# 1: 4# 2: 13# 3: 28
EVAL
:
EVAL = function(...)eval(parse(text=paste0(...)),envir=parent.frame(2))EVAL("DT[,",colname,":=cumsum(",colname,")]")# col1# 1: 4# 2: 17# 3: 45
data.table
j
eval
get()
j
set()
:=
?set
.
set(DT, j = colname, value = cumsum(DT[[colname]]))DT# col1# 1: 4# 2: 21# 3: 66
长风秋雁
TA贡献1757条经验 获得超7个赞
对于多列和应用于列值的函数。
.SD
lapply
a1 <- data.table(a=1:5, b=6:10, c1=letters[1:5])sapply(a1, class) # show classes of columns# a b c1 # "integer" "integer" "character" # column name character vectornm <- c("a", "b")# Convert columns a and b to numeric typea1[, j = (nm) := lapply(.SD, as.numeric ), .SDcols = nm ]sapply(a1, class)# a b c1 # "numeric" "numeric" "character"
- 3 回答
- 0 关注
- 567 浏览
添加回答
举报
0/150
提交
取消