Reputation: 366
I would like to append to list without needing to specify the index from a for loop. For example
I would like to use the append()
function (or similar) to get the same result as l
. Unfortunately, append()
combines all elements of tmp, tmp1
into a single vector.
tmp <- matrix(rnorm(9),3,3)
tmp1 <- matrix(rnorm(12),4,3)
l <- list(tmp,tmp1)
append(tmp,tmp1)
Thank you.
Upvotes: 0
Views: 567
Reputation: 72593
For multiple lists try list
with do.call
.
tmp1 <- tmp2 <- matrix(rnorm(9),3,3)
tmp3 <- tmp4 <- matrix(rnorm(12),4,3)
do.call(list, mget(ls(pattern='^tmp')))
# $tmp1
# [,1] [,2] [,3]
# [1,] 0.3155314 0.5651536 -0.06577049
# [2,] 0.3141578 0.4890589 0.08431155
# [3,] 0.5168662 0.3297473 1.02775261
#
# $tmp2
# [,1] [,2] [,3]
# [1,] 0.3155314 0.5651536 -0.06577049
# [2,] 0.3141578 0.4890589 0.08431155
# [3,] 0.5168662 0.3297473 1.02775261
#
# $tmp3
# [,1] [,2] [,3]
# [1,] 0.53883661 1.19557871 0.2140172
# [2,] -1.53804925 -0.08647519 0.1795095
# [3,] -1.09212014 0.19291727 0.8241137
# [4,] 0.03080796 1.75626270 2.1196755
#
# $tmp4
# [,1] [,2] [,3]
# [1,] 0.53883661 1.19557871 0.2140172
# [2,] -1.53804925 -0.08647519 0.1795095
# [3,] -1.09212014 0.19291727 0.8241137
# [4,] 0.03080796 1.75626270 2.1196755
Upvotes: 0
Reputation: 101044
Try append
with list
> append(list(tmp), list(tmp1))
[[1]]
[,1] [,2] [,3]
[1,] -1.6917740 2.2938118 -0.5994428
[2,] -0.8317474 -2.1021389 1.0077591
[3,] -0.6893888 -0.3864561 0.5299755
[[2]]
[,1] [,2] [,3]
[1,] 0.6431510 1.6601869 -0.03001407
[2,] -0.8729105 -0.8919077 0.68717777
[3,] 0.4114760 -1.4556726 -1.52659021
[4,] 1.1093545 1.0937816 1.11888348
Upvotes: 0
Reputation: 947
You can use c()
to append to preexisting list.
tmp <- matrix(rnorm(9),3,3)
tmp1 <- matrix(rnorm(12),4,3)
l <- list(tmp,tmp1)
l <- c(l, list(tmp))
l
[[1]]
[,1] [,2] [,3]
[1,] -0.2516447 -0.7518535 -0.6249582
[2,] 0.5050876 -1.7664830 0.7357084
[3,] -1.2784381 -1.0874359 0.2894429
[[2]]
[,1] [,2] [,3]
[1,] 0.1234092 -1.55219184 0.9395962
[2,] -1.1052530 1.24147499 -1.3515137
[3,] -2.1012372 -0.93570884 1.3275042
[4,] -0.1431186 -0.09361099 0.3836124
[[3]]
[,1] [,2] [,3]
[1,] -0.2516447 -0.7518535 -0.6249582
[2,] 0.5050876 -1.7664830 0.7357084
[3,] -1.2784381 -1.0874359 0.2894429
Upvotes: 3