dat-6ren">
gpt4 book ai didi

r - 在 data.table 的 j 参数中使用 "list"

转载 作者:行者123 更新时间:2023-12-04 17:33:36 26 4
gpt4 key购买 nike

我正在从 a blog post 学习 data.table 属性.我试图理解“汇总表(短和窄)”下的部分,首先将 data.frame(mtcars) 强制转换为 data.table:

> data <- as.data.table(mtcars)

> data <- data[,.(gear,cyl)]
> head(data)
gear cyl
1: 4 6
2: 4 6
3: 4 4
4: 3 6
5: 3 8
6: 3 6

到目前为止,一切都很好。

现在我已经试过了 data[, gearsL := list(list(unique(gear))), by=cyl]
> head(data)
gear cyl gearsL
1: 4 6 4,3,5
2: 4 6 4,3,5
3: 4 4 4,3,5
4: 3 6 4,3,5
5: 3 8 3,5
6: 3 6 4,3,5

我能看懂 独特(齿轮)但无法理解什么 list(list(unique(gear)) 正在做。

最佳答案

一个 data.table —— 就像任何 data.frame —— 是一个指向列向量的指针列表。

创建新列时,我们写 jDT[i,j,by]以便它评估为列列表:

DT[, (newcol_names) := list(newcol_A, newcol_B)]

那就是最外面的 list()在 OP 的示例中,对于单个 list柱子。

data[,gearsL := list(list(unique(gear))), by=cyl]


这可以而且应该使用别名 .() 来编写。 ,为清楚起见:
data[, gearsL := .(list(unique(gear))), by=cyl]

这就是您需要知道的全部内容,但我在下面进行了一些详细说明。

细节。 创建新列时,我们经常可以跳过 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()/ .()是必要的。

关于r - 在 data.table 的 j 参数中使用 "list",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33113013/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com