[英]Converting a list of differently named vectors into a dataframe with unique column names in R
The title is wordy, but i couldn't find a solution to this problem and wanted to be as specific as possible. 标题比较罗,,但我找不到解决此问题的方法,因此希望尽可能具体。 Is there an easy way to do the following:
有没有一种简单的方法可以执行以下操作:
test3 <- list('Row1'=c(a='a',b='b',c='c'), 'Row2'=c(a='d',var2='e',var3='f'))
desired dataframe
a b c var2 var3
Row1 a b c <NA> <NA>
Row2 d <NA> <NA> e f
This article - https://www.r-bloggers.com/converting-a-list-to-a-data-frame/ - seems to claim I can just use as.data.frame(test3), however when I do it, I obtain: 这篇文章- https://www.r-bloggers.com/converting-a-list-to-a-data-frame/ -好像我要求可以只使用as.data.frame(TEST3),但是当我做它,我获得:
> as.data.frame(test3)
Row1 Row2
a a d
b b e
c c f
t(as.data.frame(test3))
a b c
Row1 "a" "b" "c"
Row2 "d" "e" "f"
neither of which are right... 两者都不对...
Thanks in advance for help! 在此先感谢您的帮助!
Here is a solution with rbindlist()
from data.table
: 这是来自
data.table
rbindlist()
解决方案:
library("data.table")
test3 <- list('Row1'=c(a='a',b='b',c='c'), 'Row2'=c(a='d',var2='e',var3='f'))
rbindlist(lapply(test3, as.list), fill=TRUE)
# a b c var2 var3
# 1: a b c NA NA
# 2: d NA NA e f
The elements of your list test3
are named character vectors - so first coercing to lists. 列表
test3
的元素被命名为字符向量-因此首先强制列表。
If you want the rownames you can do: 如果需要行名,可以执行以下操作:
result <- setDF(rbindlist(lapply(test3, as.list), fill=TRUE))
rownames(result) <- names(test3)
result
# a b c var2 var3
# Row1 a b c <NA> <NA>
# Row2 d <NA> <NA> e f
This will coerce the data.table to a dataframe and then sets the rownames. 这会将data.table强制转换为数据框,然后设置行名。
For a data.table result you have to define an extra column for the rownames: 对于data.table结果,您必须为行名定义一个额外的列:
result <- rbindlist(lapply(test3, as.list), fill=TRUE)
result[, rowna := names(test3)]
result
# a b c var2 var3 rowna
# 1: a b c NA NA Row1
# 2: d NA NA e f Row2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.