NotReallyHere12
NotReallyHere12

Reputation: 98

How do I repeat an argument n times in a function?

I get this at times when making datasets. I can usually use rep, but sometimes it doesn't apply and I have to find a workaround or write an inordinately long function call.

For example, I need to make a 3-d array out of identical 2-d matrices, using the abind function. If I want 5 copies, it isn't elegant but could be worse:

mat <- matrix(c(1,0,0,0,1,0,0,0,1), nrow=3, ncol=3)
abind(mat, mat, mat, mat, mat, along=3)

If I want 200 copies, is there a cleaner solution than repeating the argument 200 times? Using rep concatenates the matrices, and I've tried other functions without any luck. I'd like to avoid loops and eval(parse(text=...)) if I can.

Upvotes: 3

Views: 467

Answers (1)

thelatemail
thelatemail

Reputation: 93813

?replicate is what you want:

replicate(5, mat)
#, , 1
#
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0    1    0
#[3,]    0    0    1
#
#  <snip!>
#  
#, , 5
#
#     [,1] [,2] [,3]
#[1,]    1    0    0
#[2,]    0    1    0
#[3,]    0    0    1

...which is a shortcut for replicate(5, mat, simplify="array"). Change the simplify= argument to FALSE or TRUE to see other possible output options.

If the abind function is needed for a different output (e.g. using along=2 for instance), then you could hack together:

do.call(abind, c(rep(list(mat), 5), along=3) )

Upvotes: 4

Related Questions