Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat matrix n-times into a list

Tags:

list

r

matrix

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)
like image 212
spesseh Avatar asked Feb 03 '14 05:02

spesseh


People also ask

How do you repeat a list and times?

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 do you repeat all elements in a list in Python?

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.


1 Answers

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().)

like image 50
Josh O'Brien Avatar answered Oct 06 '22 00:10

Josh O'Brien