[英]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
: 在Hadleyverse中,您可以使用
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. 我使用了
as_data_frame
因为它方便地允许list
列而无需额外的工作。
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' 在使用'term_id'设置'major_cd'的名称后,我们可以使用
stack
来完成此操作
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. 注意:不使用其他软件包。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.