Get for each row of list-column the length

Viewed 363

Problem: I want to find out the number of elements in a list-column (here y). Is there a more efficient and elegant way to determine this rather with purrr::map-function? This is really slow when trying to apply this to a data.table object with more than 700,000 rows.

library(data.table)

dt <- data.table(
  x = seq(4),
  y = list(c(1, 2, 3), c(2, 3), c(5, 1), c(12, 90, 200))
)

dt[, class(y)]

## more efficient/elegant way?
dt[, purrr::map(y, length)]
1 Answers

You can do:

dt[, lengths(y)]

[1] 3 2 2 3
Related