如何在 R 中组合列表?
当我们有多个列表,但它们的的数据类型相似时,我们可能需要合并这些列表。这将很有用,因为我们可以使用一个列表名称执行计算,而不是将它们应用于多个列表中。我们可以使用 mapply 函数合并多个列表。
示例
考虑以下列表 -
> List1<-list(letters[1:5],1:5,5:1,25,c("A","B","C","D")) > List1 [[1]] [1] "a" "b" "c" "d" "e" [[2]] [1] 1 2 3 4 5 [[3]] [1] 5 4 3 2 1 [[4]] [1] 25 [[5]] [1] "A" "B" "C" "D" > List2<-list(letters[6:10],6:10,c(25,16,9,4,1),36,c("Andy","Boston","Caroline","Dinesh")) > List2 [[1]] [1] "f" "g" "h" "i" "j" [[2]] [1] 6 7 8 9 10 [[3]] [1] 25 16 9 4 1 [[4]] [1] 36 [[5]] [1] "Andy" "Boston" "Caroline" "Dinesh" > mapply(c, List1, List2, SIMPLIFY=FALSE) [[1]] [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" [[2]] [1] 1 2 3 4 5 6 7 8 9 10 [[3]] [1] 5 4 3 2 1 25 16 9 4 1 [[4]] [1] 25 36 [[5]] [1] "A" "B" "C" "D" "Andy" "Boston" "Caroline" "Dinesh"
现在假设我们还有一个 List3,那么可以按如下所示将其合并 -
> List3<-list(letters[11:15],11:15,c(6,7,8,9,10),49,c("Aaron","Betty","Corie","Donald")) > List3 [[1]] [1] "k" "l" "m" "n" "o" [[2]] [1] 11 12 13 14 15 [[3]] [1] 6 7 8 9 10 [[4]] [1] 49 [[5]] [1] "Aaron" "Betty" "Corie" "Donald" > mapply(c, List1, List2, List3, SIMPLIFY=FALSE) [[1]] [1] "a" "b" "c" "d" "e" "f" "g" "h" "i" "j" "k" "l" "m" "n" "o" [[2]] [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [[3]] [1] 5 4 3 2 1 25 16 9 4 1 6 7 8 9 10 [[4]] [1] 25 36 49 [[5]] [1] "A" "B" "C" "D" "Andy" "Boston" "Caroline" "Dinesh" "Aaron" "Betty" "Corie" "Donald"
广告