将R列表转换为具有缺少/ NULL元素的数据帧 [英] Convert R list to dataframe with missing/NULL elements
问题描述
给出列表:
alist = list(
list(name="Foo",age=22),
list(name="Bar"),
list(name="Baz",age=NULL)
)
将名称和年龄列转换为数据框的最佳方式是什么,缺少值(我将按照优先顺序接受NA或)?
what's the best way to convert this into a dataframe with name and age columns, with missing values (I'll accept NA or "" in that order of preference)?
使用 ldply
的简单方法失败,因为它尝试将每个列表元素转换为数据框,但是NULL barfs因为长度不匹配。最好我现在是:
Simple methods using ldply
fail because it tries to convert each list element into a data frame, but the one with the NULL barfs because the lengths don't match. Best I have at the moment is:
> ldply(alist,function(s){t(data.frame(unlist(s)))})
name age
1 Foo 22
2 Bar <NA>
3 Baz <NA>
但这很漂亮,数值变量成为一个因素...
but that's pretty icky and the numeric variable becomes a factor...
推荐答案
提到的注释只需要一个循环,这可以通过只是将两个循环的正文放在一起:
A comment mentioned wanting only a single loop, which can be achieved with @flodel's answer just by putting the body of the two loops together:
rbind.fill(lapply(alist, function(f) {
as.data.frame(Filter(Negate(is.null), f))
}))
给
name age
1 Foo 22
2 Bar NA
3 Baz NA
这篇关于将R列表转换为具有缺少/ NULL元素的数据帧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!