Collapse data column data.table when grouping

for an object, data.tableI would like to collapse the values ​​of some grouped columns into a single object and insert the resulting objects into a new colum.

dt <- data.table(
            c('A|A', 'B|A', 'A|A', 'B|A', 'A|B'),
            c(0, 0, 1, 1, 0),
            c(22.7, 1.2, 0.3, 0.4, 0.0)
)
setnames(dt, names(dt), c('GROUPING', 'NAME', 'VALUE'))
dt
#    GROUPING NAME VALUE
# 1:      A|A    0  22.7
# 2:      B|A    0   1.2
# 3:      A|A    1   0.3
# 4:      B|A    1   0.4
# 5:      A|B    0   0.0

I think that for this you must first specify the column for which you want to group, so I should start with something like dt[, OBJECTS := <expr>, by = GROUPING].

Unfortunately, I do not know the expression <expr>to use, so the result is as follows:

#    GROUPING   OBJECTS
# 1:      A|A  <vector>
# 2:      B|A  <vector>
# 3:      A|B  <vector>

Each <vector>must contain the values ​​of the other columns. For example, the first <vector>should be a named vector equivalent to:

eg <- c(22.7, 0.3)
names(eg) <- c('0', '1')
#    0    1 
# 22.7  0.3
+5
source share
2 answers

I think this is what you are looking for:

dt1 <- dt[, list(list(setNames(VALUE, NAME))), by = GROUPING]
dt1
#    GROUPING       V1
# 1:      A|A 22.7,0.3
# 2:      B|A  1.2,0.4
# 3:      A|B        0
str(dt1)
# Classes ‘data.table’ and 'data.frame':  3 obs. of  2 variables:
# $ GROUPING: chr  "A|A" "B|A" "A|B"
# $ V1      :List of 3
#  ..$ : Named num  22.7 0.3
#  .. ..- attr(*, "names")= chr  "0" "1"
#  ..$ : Named num  1.2 0.4
#  .. ..- attr(*, "names")= chr  "0" "1"
#  ..$ : Named num 0
#  .. ..- attr(*, "names")= chr "0"
# - attr(*, ".internal.selfref")=<externalptr> 
dt1$V1
# [[1]]
#    0    1 
# 22.7  0.3 
# 
# [[2]]
#   0   1 
# 1.2 0.4 
# 
# [[3]]
# 0 
# 0 

@Arun , "data.table" setNames setattr(VALUE, 'names', NAME), :

dt1 <- dt[, list(list(setattr(VALUE, 'names', NAME))), by = GROUPING]
+3

j: , , list(.).

j list, list, :

dt[, list(allNames=list(NAME), allValues=list(VALUE)), by=GROUPING]

#    GROUPING allNames allValues
# 1:      A|A      0,1  22.7,0.3
# 2:      B|A      0,1   1.2,0.4
# 3:      A|B        0         0

@Mnel, :

dt[, lapply(.SD, list), by=GROUPING]

, <expr> :
list( c( list(), list(), ..., list() ) ) :

dt[, list(c(list(NAME), list(VALUE))), by=GROUPING]

#    GROUPING       V1
# 1:      A|A      0,1
# 2:      A|A 22.7,0.3
# 3:      B|A      0,1
# 4:      B|A  1.2,0.4
# 5:      A|B        0
# 6:      A|B        0

:

dt[, list(lapply(.SD, c)), by=GROUPING]
+5

All Articles