I recently wrote this line of code: for(i in seq_len(exponent)){out<-squareMat%*%out}
. Clearly, i
is never used and I just wanted to say "exponent
times, do out<-squareMat%*%out
". Was there a way to do this without the redundant counter i
? For example, is there an apply
family function for this?
Example - I have:
squareMat<-matrix(c(0,10,20,30),2,2)
out<-diag(nrow = nrow(squareMat))
exponent<-5
for(i in seq_len(exponent)){out<-squareMat%*%out}
out
What I want is:
squareMat<-matrix(c(0,10,20,30),2,2)
out<-diag(nrow = nrow(squareMat))
exponent<-5
[do exponent times]{out<-squareMat%*%out}
out
Yes, it does. There exist several useful functions in base R
that are not used that often these days. One of them does exactly what you want. The replicate
function replicates an expression (expr
) n
times. It works as follows, let's say that I want to generate 3 different samples of size 5 from a uniform (0 to 1) distribution. It can be easily done using replicate
. Take a look at the piece of code below
replicate(n = 3, expr = {runif(n = 5)})
# [,1] [,2] [,3]
# [1,] 0.1944426 0.5158065 0.39892501
# [2,] 0.5676580 0.9940599 0.97385575
# [3,] 0.5570141 0.2274214 0.60239883
# [4,] 0.5074303 0.3526040 0.95445298
# [5,] 0.1931812 0.4593620 0.03283596
The results are automatically organized in an array
(matrix in this case). However, you can set the parameter simplify = FALSE
. Then, the return will be a list
replicate(n = 3, expr = {runif(n = 5)}, simplify = FALSE)
# [[1]]
# [1] 0.4694347 0.9559887 0.8110113 0.7528089 0.6639614
#
# [[2]]
# [1] 0.8731027 0.7295846 0.3773571 0.5394776 0.6792322
#
# [[3]]
# [1] 0.3463870 0.3776352 0.3895620 0.2166284 0.5065204
It is important to notice that each of these replications are independent of each other. If you want something to be replicated sequentially, you have to use either a for
loop or another suitable function. There exists, for example, a function called rapply
(recursive lapply). However, it has never been clear to me the best way to use it.