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