I have a matrix that i want to duplicate n times in a list. Obviously the rep() function does not work on matrices, so does anyone have a good suggestion how to make this better than my code below?
Thanks!
# Create sample matrix
jwprox <- matrix(ncol=15,nrow=15)
# Create list of n-times matrices
jwprox <- list(jwprox,jwprox,jwprox)
To repeat the elements of the list n times, we will first copy the existing list into a temporary list. After that, we will add the elements of the temporary list to the original list n times using a for loop, range() method, and the append() method.
How to Repeat Each Element k Times in a List in Python? To repeat the elements in a list in python, we insert the elements of a given list to a new list repeatedly. To repeat each element k times in a list, we will insert each element of the existing k times in the new list.
You can use either lapply()
n <- 3
x <- lapply(seq_len(n), function(X) jwprox)
str(x)
# List of 3
# $ : logi [1:15, 1:15] NA NA NA NA NA NA ...
# $ : logi [1:15, 1:15] NA NA NA NA NA NA ...
# $ : logi [1:15, 1:15] NA NA NA NA NA NA ...
or replicate()
:
xx <- replicate(n, jwprox, simplify=FALSE)
identical(x,xx)
# [1] TRUE
(FWIW, replicate()
is just a sometimes-handy wrapper for sapply()
and, in turn, lapply()
.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With