简体   繁体   中英

convert lists of lists of vectors to dataframe in R

I have a list of list of character vectors, in the form of the following:

terms <- list(
    term_id = c("1", "2", "3"),
    major_cd = list(
      c("ABCD", "AS56"),
      c("RCPZ", "AS56"),
      c("RCET", "ABCD", "RCPZ", "AS56")
    )
  )

I want to create a dataframe like:

> df
  term_id major_cd
1  "1"      "ABCD"
2  "1"      "AS56"
3  "2"      "RCPZ"
4  "2"      "AS56"
5  "3"      "RCET"
6  "3"      "ABCD"
7  "3"      "RCPZ"
8  "3"      "AS56"
> class(df)
[1] "data.frame"

In the Hadleyverse, you could use unnest :

library(dplyr)
library(tidyr)
as_data_frame(terms) %>% unnest
## Source: local data frame [8 x 2]
## 
##   term_id major_cd
##     (chr)    (chr)
## 1       1     ABCD
## 2       1     AS56
## 3       2     RCPZ
## 4       2     AS56
## 5       3     RCET
## 6       3     ABCD
## 7       3     RCPZ
## 8       3     AS56

I've used as_data_frame since it conveniently allows list columns without extra work.

you can just do it like this:

   df <- data.frame(
      term_id = rep(terms$term_id, lengths(terms$major_cd),
      major_cd = unlist(terms$major_cd)
    )

  term_id major_cd
1       1     ABCD
2       1     AS56
3       2     RCPZ
4       2     AS56
5       3     RCET
6       3     ABCD
7       3     RCPZ
8       3     AS56

We could do this with stack after setting the names of 'major_cd' with 'term_id'

res <- stack(with(terms, setNames(major_cd, term_id)))[2:1]
res
#  ind values
#1   1   ABCD
#2   1   AS56
#3   2   RCPZ
#4   2   AS56
#5   3   RCET
#6   3   ABCD
#7   3   RCPZ
#8   3   AS56

If needed, we can change the column names

colnames(res) <- names(terms)

NOTE: No additional packages used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM