如何将具有不同长度元素的列表转换为数据框
问题描述:
在这里,当我遇到循环时,我经常遇到这种问题.第一个解决了.
Here I meet so often this kind of problem when I have a loop. The first one is solved.
[1]我有一个这样的列表:
[1] I have a list like this:
myList <- list(a = c(1, 2, 3), b = c(4, 5, 6, 7), c= c(9,10))
现在我要像这样将列表转换为data.frame:
now I want to convert the list to a data.frame like this:
Value
a 1, 2, 3
b 4, 5, 6, 7
c 9, 10
有人用基本R向我展示通用功能吗?
Does anyone show me a general function by basic R?
[2]出现新问题:
mynewList <- list(a = c(1, 2, 3, "f"), b = c(4, 5, 6), c= c(9,10), d=list(1,2))
我想将mynewlist转换为这样的数据框:
I want to convert the mynewlist to a dataframe like this:
a b c d
1 1 4 9 1
2 2 5 10 2
3 3 6 na na
4 f na na na
我以前使用下面的命令,它不带d元素即可工作.但它暂时不起作用.
I use the below command before, it works without the d element. but it didnot work for now.
df<-data.frame(lapply(myList, "length<-" , max(lengths(myList))))
有人用基本R向我展示通用功能吗?
Does anyone show me a general function by basic R?
答
1.我们可以使用
2.我们可以在应用最大长度之前
2. We can
1.我们可以使用 sapply
和 paste
:
df <- data.frame(Value = sapply(myList, paste, collapse = ','))
输出:
Value
a 1,2,3
b 4,5,6,7
c 9,10
2.我们可以在应用最大长度之前 unlist
每个列表元素:
2. We can unlist
each list element before applying max lengths:
df <- data.frame(lapply(mynewList, function(x) {
x <- unlist(x)
length(x) <- max(lengths(mynewList))
return(x)
}))
输出:
a b c d
1 1 4 9 1
2 2 5 10 2
3 3 6 NA NA
4 f NA NA NA