在 j 中使用大括号 {...}

Use of braces {...} in j

我一直在学习名为“R 中的数据分析,data.table 方式”的数据营课程。

练习说明如下,

布局如下,

# This is your data.table `DT`. The keys are set to `A` and `B`
DT <- data.table(A = letters[c(2,1,2,3,1,2,3)], B = c(5,4,1,9,8,8,6), C = 6:12)
setkey(DT, A, B)
# Select the `b` group
# `b` and `c` groups
# The first row of the `b` and `c` group
# `by=.EACHI` and `.SD` 
# Print out all the data in the two groups before you return
# the first and last row of each group again. Use {} and .N

我确实明白前 4 条是如何完成的,但是当我继续执行最后一条指令时,我卡住了。我不明白如何使用 {},最终我发现解决方案是:

DT[c("b", "c"), {print(.SD); .SD[c(1, .N)]}, by = .EACHI]

我不明白j中的语法是如何工作的,谁能给我解释一下?谢谢。

正如您从阅读 help("data.table") 中了解到的,j 预计

A single column name, single expresson of column names, list() of expressions of column names, an expression or function call that evaluates to list (including data.frame and data.table which are lists, too), or (when with=FALSE) a vector of names or positions to select.

您还应该阅读 help("{"){ 可以组合表达式。它 returns 最后计算的表达式。因此,就 data.table 而言,它只得到最后一个表达式,即 .SD[c(1, .N)],并且它知道如何处理它(例如,合并每个组的结果)。 data.table 不需要知道如何处理 print(.SD),但它是在 data.table 的框架内评估的。