你可以使用c()函数或append()函数来组合R中的两个或多个列表:
#combine two lists using c()
combined <- c(list1, list2)
#combine two lists using append()
combined <- append(list1, list2)
这两个函数将产生相同的结果。
下面的例子展示了如何在实践中使用这种语法。
例子 1: 合并两个列表
下面的代码显示了如何在 R 中组合两个列表:
#define lists
list1 <- list(2, 5, 6, 8)
list2 <- list(A = 1:5, B = 3)
#combine two lists into one
combined <- c(list1, list2)
#view combined list
combined
[[1]]
[1] 2
[[2]]
[1] 5
[[3]]
[1] 6
[[4]]
[1] 8
$A
[1] 1 2 3 4 5
$B
[1] 3
我们也可以使用**length()**函数来得到合并后的列表的长度:
#get length of combined list
length(combined)
[1] 6
我们也可以使用**class()**函数来获得合并后的列表的类别:
#get class of combined list
class(combined)
[1] "list"
例子 2: 合并两个以上的列表
我们可以使用类似的语法在 R 中组合两个以上的列表:
#define lists
list1 <- list(2, 5, 6, 8)
list2 <- list(A = 1:5, B = 3)
list3 <- list(X = 'A', Y = 'B')
#combine three lists into one
combined <- c(list1, list2, list3)
#view combined list
combined
[[1]]
[1] 2
[[2]]
[1] 5
[[3]]
[1] 6
[[4]]
[1] 8
$A
[1] 1 2 3 4 5
$B
[1] 3
$X
[1] "A"
$Y
[1] "B"
其他资源
下面的教程提供了关于R语言中列表的额外信息: