If you want to unlist the lists in the context of the dataframe you have to decide if you want them in a long or wide format, e.g.
Data
library(dplyr)
library(tidyr)
df <- tibble(CADM1 = c(list(c(12, 34, 2)), list(c(1, 2)),
list(c(12, 34, 2, 33)), list(c(2))))
df
# A tibble: 4 × 1
CADM1
<list>
1 <dbl [3]>
2 <dbl [2]>
3 <dbl [4]>
4 <dbl [1]>
long format
df %>%
unnest(CADM1)
# A tibble: 10 × 1
CADM1
<dbl>
1 12
2 34
3 2
4 1
5 2
6 12
7 34
8 2
9 33
10 2
wide format (needs to introduce NA
s to pad the length of each list)
df %>%
unnest_wider(CADM1, names_sep="_")
# A tibble: 4 × 4
CADM1_1 CADM1_2 CADM1_3 CADM1_4
<dbl> <dbl> <dbl> <dbl>
1 12 34 2 NA
2 1 2 NA NA
3 12 34 2 33
4 2 NA NA NA
provided data
Using your example (I replaced NULL
with NA
because NULL
brings some special behavior with it...)
example_df_wider$receptor_1[2] <- NA
example_df_wider$receptor_2[1] <- NA
example_df_wider
# A tibble: 2 × 3
cell_type receptor_1 receptor_2
<fct> <list> <list>
1 cell_1 <dbl [2]> <lgl [1]>
2 cell_2 <lgl [1]> <dbl [2]>
long format
example_df_wider %>%
unnest(starts_with("rec"))
# A tibble: 4 × 3
cell_type receptor_1 receptor_2
<fct> <dbl> <dbl>
1 cell_1 1 NA
2 cell_1 1 NA
3 cell_2 NA 1
4 cell_2 NA 1
wide format
example_df_wider %>%
unnest_wider(receptor_1, names_sep="_") %>%
unnest_wider(receptor_2, names_sep="_")
# A tibble: 2 × 5
cell_type receptor_1_1 receptor_1_2 receptor_2_1 receptor_2_2
<fct> <dbl> <dbl> <dbl> <dbl>
1 cell_1 1 1 NA NA
2 cell_2 NA NA 1 1
Sum the values
example_df_wider %>%
unnest(starts_with("rec")) %>%
group_by(cell_type) %>%
summarize(across(starts_with("rec"), ~ sum(.x, na.rm=T)))
# A tibble: 2 × 3
cell_type receptor_1 receptor_2
<fct> <dbl> <dbl>
1 cell_1 2 0
2 cell_2 0 2