I am trying to use the dplyr function case_when() on a list of annotation so I can assign the name of the marker to my data. I've found a way to do this manually by writing it several times but I tried applying it to a list with apply or map and didn't find a solution.
Here is a reproductible example :
library(tidyverse)
annotation <- list (marker_1 = c("L", "D"),
marker_2 = c("C","R"),
marker_3 = c("A", "B"),
marker_4 = c("E", "F"),
marker_5 = c("G", "H"))
df <- tibble(L = 1, D = 2, C = 3, R = 4)
annotation_df <-
tibble(markers = colnames(df)) %>%
mutate(
type = case_when(
markers %in% annotation[[1]] ~ names(annotation[1]),
markers %in% annotation[[2]] ~ names(annotation[2]),
markers %in% annotation[[3]] ~ names(annotation[3]),
markers %in% annotation[[4]] ~ names(annotation[4]),
markers %in% annotation[[5]] ~ names(annotation[5])
)
) %>%
column_to_rownames("markers")
print(annotation_df)
#> type
#> L marker_1
#> D marker_1
#> C marker_2
#> R marker_2
Created on 2022-04-25 by the reprex package (v2.0.1)