Calculate length of multiple lists within a data.table

Viewed 91

I would like to calculate the length of each element of a list within a data.table. Here is a small example.

test<-data.table(
  x = list(c(1,2,3),c(1)),
  y = list(c(2,3),c(1,2,3))
)

#This works:
test[,length_x:=sapply(x,length)]
test[,length_y:=sapply(y,length)]

#But this does not, can somebody explain why and how to correct it:
test[,c("length_x","length_y"):=sapply(.SD,length)]

Can somebody explain why the second part of the code does not work and how to correct it.

2 Answers

Te issue here is that you actually need two levels of iteration

  • Iteration over the columns with lapply(.SD, ...)
  • Iteration over the column elements to evaluate a "cellwise" length
test[, c("length_x", "length_y") := lapply(.SD, function(column) {
  sapply(column, length)
})]

This can be simplified further using the ellipses (...) in lapply.

test[, c("length_x", "length_y") := lapply(.SD, sapply, length)]

Try lengths within data.table like below

> test[, paste0("length_", names(test)) := Map(lengths, .SD)][]
       x     y length_x length_y
1: 1,2,3   2,3        3        2
2:     1 1,2,3        1        3
Related