美文网首页
R data.frame convert to list

R data.frame convert to list

作者: 倪桦 | 来源:发表于2022-12-18 18:05 被阅读0次

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"

相关文章

网友评论

      本文标题:R data.frame convert to list

      本文链接:https://www.haomeiwen.com/subject/xcpeqdtx.html