使用括号()来对data.table列进行子集化

时间:2016-05-23 12:37:46

标签: r data.table subset parentheses

在分配(通过引用)的情况下,'with = FALSE'可以由括号“()”中的LHS替换。简单地在没有赋值的情况下对列进行子集化时,这个好的功能不起作当然有.SD / .SDcols或get()/ mget()的工作量,但是以相同的方式对列进行子集会很好,无论是否有赋值。

dt  <- data.table(A = 1:3, B = 4:6 )
col  <- "A"
cols  <- c("A","B")

# assign the old way
dt[,  col  :=     9 , with=FALSE]         
dt[,  cols := .(9,8), with=FALSE]

# assign the new way
dt[, (col)  :=     8 ]        
dt[, (cols) := .(8,7)]      

# But the above syntax does not work for subsetting
dt[, (col)]
dt[, (cols)]

# I know how I can subset col and cols, but that is not the question here, 
# e.g.:
dt[,  col,  with=FALSE]
dt[,  cols, with=FALSE]
dt[, .SD, .SDcols=col]
dt[, .SD, .SDcols=cols]

# Below, further (there are even more) types of subsetting but they are not 
# the same for col and cols, which is importent for looping where I dont 
# know how many cols I call in advance.

dt[, get(col)]
dt[, mget(cols)]
dt[[col]] # Returns a vector, nor running: dt[[cols]] 

换句话说:如果dt [,(col):= 8]运行,作为一个天真的用户,我期望df [,(col)]也能运行。可能在[data.table中存在冲突,因此无法实现?

0 个答案:

没有答案