user66794
user66794

Reputation: 73

Use of braces {...} in j

I have been studying a datacamp course called "Data Analysis in R, the data.table Way".

The instruction of the exercise is as follows,

The layout is as follows,

# 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

I do understand how the first 4 to be done but then when I proceed to the last instruction I got stuck. I do not understand how {} can be used and eventually I found out that the solution for that is:

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

I do not understand how the syntax in j works, may anyone explain it to me? Thanks.

Upvotes: 6

Views: 1110

Answers (1)

Roland
Roland

Reputation: 132576

As you know from reading help("data.table"), j expects

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.

You should also read help("{"). { can combine expressions. It returns the last evaluated expression. Thus, as far as data.table is concerned it only gets handed the last expression, i.e., .SD[c(1, .N)], and it knows what to do with that (e.g., combine the results for each group). data.table doesn't need to know what to do with print(.SD), which however is evaluated within the data.table's frame.

Upvotes: 8

Related Questions