1.Test data
data <- data.frame( names = rep(c("aaa","bbb","ccc"),c(3,8,5)), elements = stringi::stri_rand_strings(16,3, pattern = "[A-Za-z0-9]"))
-------------------------
> data
names elements
1 aaa gdz
2 aaa cDR
3 aaa 06b
4 bbb GQH
5 bbb nnS
6 bbb X2i
7 bbb rsV
8 bbb kaU
9 bbb Vvd
10 bbb 0nF
11 bbb 34o
12 ccc pSi
13 ccc lmP
14 ccc jdf
15 ccc 0zz
16 ccc lVL
2.Convert to list
data %>% mutate(n = seq(n())) %>% select(n,names,elements) %>%
tidyr::pivot_wider(names_from = names,values_from = elements,values_fill = NA) %>%
tibble::column_to_rownames("n") %>% as.list() %>%
lapply(function(x){unique(x[!is.na(x)])}) ## drop NULL and NA
-------------------------
$aaa
[1] "gdz" "cDR" "06b"
$bbb
[1] "GQH" "nnS" "X2i" "rsV" "kaU" "Vvd"
[7] "0nF" "34o"
$ccc
[1] "pSi" "lmP" "jdf" "0zz" "lVL"
网友评论