当我们有多个列表但它们具有相似的数据类型时,我们可能想要合并或合并这些列表。这将有助于使用,因为我们可以使用一个列表名称执行计算,而不是将其应用于多个列表名称。我们可以借助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"