R语言 把列表转换为数据框架

R语言 把列表转换为数据框架

在这篇文章中,我们将讨论如何在R编程语言中把一个列表转换为数据框架。我们将按行和按列将列表转换为数据框。

例1: R程序在一个数字和字符类型的列表中创建三个列表,并按列转换为数据框架。

语法 as.data.frame(do.call(cbind, list_name))

参数: 其中cbind是将列表按列转换为数据框架,list_name是输入的列表,是列表的列表。

代码

# create list and create 3 lists 
# inside this list
lists = list(list1 = list(1, 2, 3, 4, 5),
             list2 = list('a', 'b', 'c', 'd', 'e'),
             list3 = list(2, 3, 4, 5, 6))
  
# convert list of lists into dataframe
# by column
print(as.data.frame(do.call(cbind, lists)))
R

输出:

  list1 list2 list3
1     1     a     2
2     2     b     3
3     3     c     4
4     4     d     5
5     5     e     6
R

例2: R程序在一个数字和字符类型的列表中创建两个列表,并按列转换为数据框架

# create list and create 2 lists 
# inside this list
lists = list(list1 = list(1, 2, 3, 4, 5),
             list2 = list('a', 'b', 'c', 'd', 'e'))
  
# convert list of lists into
# dataframe by column
print(as.data.frame(do.call(cbind, lists)))
R

输出:

  list1 list2
1     1     a
2     2     b
3     3     c
4     4     d
5     5     e
R

例3: R程序在一个列表内创建三个数字和字符类型的列表,并按列转换为数据框架。

语法: as.data.frame(do.call(rbind,list_name))

参数: 其中rbind是按行将列表转换为数据框架,list_name是输入的列表,是列表的列表。

# create list and create 3 lists 
# inside this list
lists = list(list1 = list(1, 2, 3, 4, 5),
             list2 = list('a', 'b', 'c', 'd', 'e'),
             list3 = list(2, 3, 4, 5, 6))
  
# convert list of lists into dataframe 
# by row
print(as.data.frame(do.call(rbind, lists)))
R

输出:

      V1 V2 V3 V4 V5
list1  1  2  3  4  5
list2  a  b  c  d  e
list3  2  3  4  5  6
R

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程