Add vectors/matrices to a list of vectors/matrices
我有一个向量或矩阵列表,如下所示:
1 2 3 4 5 6 7 | l <- list(1:3, 4:6) l # [[1]] # [1] 1 2 3 # [[2]] # [1] 4 5 6 |
现在我想在列表中添加一个新的向量/矩阵。使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | c(l, 7:9) # [[1]] # [1] 1 2 3 # [[2]] # [1] 4 5 6 # [[3]] # [1] 7 # [[4]] # [1] 8 # [[5]] # [1] 9 |
也
1 2 3 4 5 6 7 8 9 10 | list(l, 7:9) # [[1]] # [[1]][[1]] # [1] 1 2 3 # [[1]][[2]] # [1] 4 5 6 # [[2]] # [1] 7 8 9 |
解决这个问题的标准方法是什么?
1 2 3 4 5 6 7 8 9 | do.call(c, list(l, list(7:9))) # [[1]] # [1] 1 2 3 # [[2]] # [1] 4 5 6 # [[3]] # [1] 7 8 9 |
如果它是一个矩阵:
1 2 3 4 5 6 7 8 9 10 11 12 | do.call(c, list(l, list(matrix(7:9)))) # [[1]] # [1] 1 2 3 # [[2]] # [1] 4 5 6 # [[3]] # [,1] # [1,] 7 # [2,] 8 # [3,] 9 |
如果要添加多个向量或矩阵,可以将它们全部放在第二个列表中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | do.call(c,list(l, list(matrix(7:9), 6:10))) # [[1]] # [1] 1 2 3 # [[2]] # [1] 4 5 6 # [[3]] # [,1] # [1,] 7 # [2,] 8 # [3,] 9 # [[4]] # [1] 6 7 8 9 10 |