How can I enter a column of lists in data.table

Following this post , I have another question about list columns in data.table.

DT = data.table(x=list(c(1,2),c(1,2),c(3,4,5)))

It seems you cannot type a column of lists.

DT[,y:=.I,by=x]
Erreur dans `[.data.table`(DT, , `:=`(y, .I), by = x) :
  The items in the 'by' or 'keyby' list are length (2,2,3). Each must be same length as rows in x or number of rows returned by i (3).

I thought I could with lists of the same length, but:

DT = data.table(x=list(c(1,2),c(1,2),c(3,5)))
DT[,y:=.I,by=x]
Erreur dans `[.data.table`(DT, , `:=`(y, .I), by = x) :
  The items in the 'by' or 'keyby' list are length (2,2,2). Each must be same length as rows in x or number of rows returned by i (3).

Is there a workaround? If not about calling a function?

+5
source share
1 answer

I would do something like this as a workaround:

DT[, y := which(DT$x %in% x), by = 1:nrow(DT)]

This always returns the first matching index, which will serve as the group identifier.

You should do something like this:

DT[, psnInGrp := seq_along(x), by=y]

#        x y psnInGrp
# 1:   1,2 1        1
# 2:   1,2 1        2
# 3: 3,4,5 3        1
+3
source

All Articles