Repeat matrix n-times into a list

天涯浪子 提交于 2019-12-30 23:49:29

问题


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)

回答1:


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



来源:https://stackoverflow.com/questions/21520552/repeat-matrix-n-times-into-a-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!