henrik
henrik

Reputation: 95

Converting a column of lists to its length

I have a dataframe with a column consisting of lists. I wish to mutate to create a new value for each row containing the length of each of these lists, but I'm having trouble doing that

I've tried

df <- data.frame(a=1:3,b=I(list(1,1:2,1:3)))

df %>%  mutate(len = length(b))

but this just sets len to the the number of rows in the dataframe (value of len is 3 for every row). Any help would be greatly appreciated!

Upvotes: 0

Views: 44

Answers (2)

akrun
akrun

Reputation: 887128

We can do unnest and create the new column

library(tidyverse)
df %>% 
   unnest %>%
   group_by(a) %>% 
   mutate(c = n())

Upvotes: 0

henrik
henrik

Reputation: 95

Figured it out, use

df %>%  mutate(len = lengths(b))

Upvotes: 1

Related Questions