How to count elements in each column of a list column in data frame in R

Viewed 1207

I have a data frame df where one of the column is a list column. Each of the element of this column in dataframe is list. So how do I include (mutate) a new column in df giving me a count of corresponding elements in that list column.

sample data

df <- structure(list(x1 = 1:5, 
                     x2 = list(c("a", "b"), c("b", "c", "d"), c("a", "b"), c("a", "b"), c("a", "b"))), 
                row.names = c(NA, -5L), class = c("tbl_df", "tbl", "data.frame"))
> df
# A tibble: 5 x 2
     x1 x2       
  <int> <list>   
1     1 <chr [2]>
2     2 <chr [3]>
3     3 <chr [2]>
4     4 <chr [2]>
5     5 <chr [2]>

I have tried this but to no avail

df %>% mutate(x3 = length(x2[[row_number()]]))

Error: Problem with `mutate()` input `x3`.
x recursive indexing failed at level 2

i Input `x3` is `length(x2[[row_number()]])`.
Run `rlang::last_error()` to see where the error occurred.

My desired out put is something like

# A tibble: 5 x 3
     x1 x2           x3
  <int> <list>    <int>
1     1 <chr [2]>     2
2     2 <chr [3]>     3
3     3 <chr [2]>     2
4     4 <chr [2]>     2
5     5 <chr [2]>     2
3 Answers

Try lengths, which counts the number of elements in each row.

df$x3 <- lengths(df$x2)
df
#   x1      x2 x3
# 1  1    a, b  2
# 2  2 b, c, d  3
# 3  3    a, b  2
# 4  4    a, b  2
# 5  5    a, b  2

A tidyverse alternative is to use rowwise:

df %>% rowwise() %>% mutate(x3 = length(x2))
# A tibble: 5 x 3
# Rowwise: 
     x1 x2           x3
  <int> <list>    <int>
1     1 <chr [2]>     2
2     2 <chr [3]>     3
3     3 <chr [2]>     2
4     4 <chr [2]>     2
5     5 <chr [2]>     2

Using map

library(dplyr)
library(purrr)
df %>% 
   mutate(x3 = map_int(x2, length))
Related