Hi all,
I have data frame with 1 named list column that I need to widen. However, when I widen, the names of each element of the list column becomes an empty string. I need to keep these names for downstream scripts that depend on them.
Hack solution 1:
- All elements on the same row are named the same as the tissue value for that row.
- Figure out a way of applying that value to each name
- Something like:
test %>% rowwise %>% mutate(across(!tissue), .fns = names(.x) <- tissue)
Hack Solution 2 (works but not elegant):
names(test$res_Low_v_High_in_T1) <- test$tissue
names(tests$res_Low_v_High_in_T2) <- test$tissue
names(test$res_T2_v_T1_in_High) <- test$tissue
names(test$res_T2_v_T1_in_Low) <- test$tissue
names(test$res_trial_interaction) <- test$tissue
Does anyone know how to preserve the names (ideally) or to apply hack solution 1?
Thanks all in advance.
Kenneth
Original data frame in long format:
> deseq2_results
# A tibble: 25 × 3
tissue contrast results
<chr> <chr> <named list>
1 Duodenum res_Low_v_High_in_T1 <tibble [15,714 × 15]>
2 Duodenum res_Low_v_High_in_T2 <tibble [15,714 × 15]>
3 Duodenum res_T2_v_T1_in_High <tibble [15,714 × 15]>
4 Duodenum res_T2_v_T1_in_Low <tibble [15,714 × 15]>
5 Duodenum res_trial_interaction <tibble [15,714 × 15]>
6 Ileum res_Low_v_High_in_T1 <tibble [16,069 × 15]>
7 Ileum res_Low_v_High_in_T2 <tibble [16,069 × 15]>
8 Ileum res_T2_v_T1_in_High <tibble [16,069 × 15]>
9 Ileum res_T2_v_T1_in_Low <tibble [16,069 × 15]>
10 Ileum res_trial_interaction <tibble [16,069 × 15]>
# ℹ 15 more rows
# ℹ Use `print(n = ...)` to see more rows
> names(deseq2_results$results)
[1] "Duodenum" "Duodenum" "Duodenum" "Duodenum" "Duodenum" "Ileum" "Ileum" "Ileum" "Ileum" "Ileum" "Jejunum"
[12] "Jejunum" "Jejunum" "Jejunum" "Jejunum" "Liver" "Liver" "Liver" "Liver" "Liver" "Muscle" "Muscle"
[23] "Muscle" "Muscle" "Muscle"
Final data frame in wide format:
> test <- deseq2_results %>%
tidyr::pivot_wider(
names_from = contrast,
values_from = results
)
> test[,1:2] # just showing one of the new columns
# A tibble: 5 × 2
tissue res_Low_v_High_in_T1
<chr> <named list>
1 Duodenum <tibble [15,714 × 15]>
2 Ileum <tibble [16,069 × 15]>
3 Jejunum <tibble [15,889 × 15]>
4 Liver <tibble [14,325 × 15]>
5 Muscle <tibble [13,159 × 15]>
> names(test$res_Low_v_High_in_T1)
[1] "" "" "" "" ""