How to recycle an [x, y] vector while adding a 2 x z matrix?

Viewed 38

How can I do this without the first replicate using recycling or matrix multiplication?

replicate(5, c(-74.04456199608506, 40.68923184725649)) + replicate(5, rnorm(2))
2 Answers

You could use sweep():

x <- replicate(5, rnorm(2))
sweep(x, 1, c(-74.04456199608506, 40.68923184725649), FUN = `+`) 

Results check:

identical(replicate(5, c(-74.04456199608506, 40.68923184725649)) + x,
          sweep(x, 1, c(-74.04456199608506, 40.68923184725649), FUN = `+`))

[1] TRUE

You could just use +, therefore using recycling:

replicate(5, rnorm(2)) + c(-74.04456199608506, 40.68923184725649)

output

          [,1]      [,2]      [,3]      [,4]      [,5]
[1,] -74.30676 -75.55923 -74.57547 -73.35665 -75.33159
[2,]  39.11709  39.08770  39.22748  42.78934  41.47697
Related