What is the difference between passing one column to j and choosing the same column from the data table.

I have a data table containing nameand class. Each namebelongs to one class. Here is an example dataset.

library(data.table)
DT <- data.table(name = c("John","Smith","Jane","Ruby","Emerald","Jasmine","Tulip"),
             class = c(1,2,3))

I want to create a column that contains all the students in the class to which the person belongs. This is how I do it and it works.

DT[, class.students := paste(.SD), .SDcols = "name", by = "class"]

I am trying to understand why the following does not work, i.e. it does not evaluate the function according to the list of everyone namein the group (it returns only the namerow value in the created column)

DT[, class.students := paste(name), by = "class"]

Especially when the code below with maxworks as expected, i.e. evaluates all elements in a group and returns the same value for each group.

DT[, class.students := max(name), by = "class"]

What am I missing here?

EDIT: max - , , .SDcols, , , , .

+4
1

.SD - list, , ( str).

paste(list(letters[1:3])) #not the desirable output
#[1] "c(\"a\", \"b\", \"c\")"

paste(letters[1:3]) #did not change anything
#[1] "a" "b" "c"

paste sep collapse

paste(letters[1:3], collapse=", ")
#[1] "a, b, c"

OP,

DT[, class.students := paste(name, collapse=", "), by = class]

.SD, , list vector [[, unlist ..

DT[,  class.students := paste(unlist(.SD), collapse=", "), by = class]

DT[, class.students := paste(.SD[[1]], collapse=", "), by = class]

str(DT) ,


.SD - , list. .SD , . data.frame, , lapply

DT[, class.students := lapply(.SD, paste, collapse=", "), by = class]

.SDcols, . , .SDcols .

str(DT)
#Classes ‘data.table’ and 'data.frame':  7 obs. of  3 variables:
# $ name          : chr  "John" "Smith" "Jane" "Ruby" ...
# $ class         : num  1 2 3 1 2 3 1
# $ class.students: chr  "John, Ruby, Tulip" "Smith, Emerald" "Jane, Jasmine" "John, Ruby, Tulip" ...
# - attr(*, ".internal.selfref")=<externalptr> 
+3

Source: https://habr.com/ru/post/1668841/


All Articles