3 回答

TA貢獻1891條經(jīng)驗 獲得超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
帶著 :=
現(xiàn)在所有情況下都不推薦使用,因為將lhs包裝在 :=
使用括號已經(jīng)有一段時間了。 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條經(jīng)驗 獲得超7個贊
對于多列和應(yīng)用于列值的函數(shù)。
.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 關(guān)注
- 597 瀏覽
添加回答
舉報