如何将具有不同长度元素的列表转换为数据框 [英] How to convert a list with different length element to a dataframe

查看:47
本文介绍了如何将具有不同长度元素的列表转换为数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这里,当我遇到循环时,我经常遇到这种问题.第一个解决了.

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.我们可以使用 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

这篇关于如何将具有不同长度元素的列表转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆