R语言 把嵌套列表转换为数据框架
在这篇文章中,我们将讨论如何在R编程语言中把嵌套列表转换为数据框架。
它可以通过两种方法完成 。
- 通过列将嵌套列表转换为数据框。
- 将嵌套列表转换为按行的数据框架。
首先,让我们创建一个嵌套列表。
代码块
输出:
图1:嵌套列表
方法1: 将嵌套列表按列转换为数据框架。
方法
- 使用do.call和cbind的data.fram函数创建数据框架。
- cbind用于将列表按列绑定到数据框架中。
- do.call用于将cbind和嵌套列表绑定在一起,作为数据框架函数的一个参数。
- 同时,将整个数据框架存储在一个名为data_frame的变量中并打印该变量。
代码
# list() functions are used to create
# the list and those list() functions
# are put in another list() function to
# make the nested list
nested_list <- list(l1 = list(1:5, 5:1 ),
l2 = list(100:105, 105:100 ),
l3 = list(200:205, 205:200 ))
# Convert nested list to data frame
# by column with the help of cbind and do.call
data_frame <- as.data.frame(do.call(cbind, nested_list))
# Print data frame
data_frame
输出:
l1 l2 l3
1 1, 2, 3, 4, 5 100, 101, 102, 103, 104, 105 200, 201, 202, 203, 204, 205
2 5, 4, 3, 2, 1 105, 104, 103, 102, 101, 100 205, 204, 203, 202, 201, 200
方法2: 按行将嵌套列表转换为数据框。
方法
- 使用do.call和rbind的data.fram函数创建数据框架。
- rbind用于将列表按行绑定到数据框中。
- do.call用于将rbind和嵌套的列表绑定在一起,作为数据框架函数的一个参数。
- 同时,将整个数据框架存储在一个名为data_frame的变量中并打印该变量。
代码
# list() functions are used to create
# the list and those list() functions
# are put in another list() function to
# make the nested list
nested_list <- list(l1 = list(1:5, 5:1 ),
l2 = list(100:105, 105:100 ),
l3 = list(200:205, 205:200 ))
# print the nested list
nested_list
# Convert nested list to data frame by row
# with the help of rbind and do.call
data_frame <- as.data.frame(do.call(rbind, nested_list))
# Print data frame
data_frame
输出:
V1 V2
l1 1, 2, 3, 4, 5 5, 4, 3, 2, 1
l2 100, 101, 102, 103, 104, 105 105, 104, 103, 102, 101, 100
l3 200, 201, 202, 203, 204, 205 205, 204, 203, 202, 201, 200