与任何 data.frame 一样,data.table 是指向列向量的指针列表。
创建新列时,我们写j
of DT[i,j,by]
以便其计算结果为列列表:
DT[, (newcol_names) := list(newcol_A, newcol_B)]
这就是最外面的list()
在OP的例子中,对于单个list
column.
data[,gearsL := list(list(unique(gear))), by=cyl]
这可以而且应该使用别名来编写.()
,为了清楚起见:
data[, gearsL := .(list(unique(gear))), by=cyl]
这就是您需要知道的全部内容,但我在下面进行了一些详细说明。
Details.创建新列时,我们常常可以跳过list()
/.()
:
DT = data.table(id=1:3)
DT[, E := c(4,5,6)]
DT[, R := 3]
# this works as if we had typed
# R := c(3,3,3)
注意E
枚举每个值,同时R
在所有行上回收单个值。下一个例子:
DT[, Elist := list(hist(rpois(1,1)), hist(rpois(2,2)), hist(rpois(3,3)))]
正如我们所做的那样E
,我们枚举的值Elist
这里。这里仍然使用快捷方式;list()
在这里只是因为该列本身就是一个list
,经证实
sapply(DT, class)
# id E R Elist
# "integer" "numeric" "numeric" "list"
便捷的跳过快捷方式list()
/.()
在一种特殊情况下会失败:当我们创建一个list
回收其值的列:
DT[, Rlist := list(c("a","b"))]
# based on the pattern for column R, this should work as if we typed
# Rlist := list(c("a","b"), c("a","b"), c("a","b"))
它不起作用,因为解析器将其视为C2 := .( c("a", "b") )
并认为我们只是忽略了对每一行使用一个值进行完整枚举,例如Elist
做。要获得所需的结果,请跳过快捷方式并将向量包装在list()
/.()
:
DT[, Rlist := .(list(c("a","b")))]
# id E R Elist Rlist
# 1: 1 4 3 <histogram> a,b
# 2: 2 5 3 <histogram> a,b
# 3: 3 6 3 <histogram> a,b
这是OP示例中的情况,其中外部list()
/.()
是必要的。