0

I'm sure this is a simple one. I have two vectors 'd' and 'r'. I would like to calculate t=(d+r)/d for all combinations of d and r. Thus, I would like to end up with a matrix where t is calculated for each d using each value of r.

Output should look something like this: https://www.dropbox.com/s/hf74s4jz2qe3st7/table.jpg?dl=0

I've tried a for loop and also looked at apply but so far unsuccessfully.

I hope someone can help.

EDIT: This is the for loop i tried:

t<-matrix(nrow=length(d), ncol=length(r))
for(i in 1:length(r)){
       t[i]=(d+r[i])d
      }

didn't work :(

  • 3
    You probably are looking for `outer`. For more help, please take a look at these tips on how to produce a [minimum, complete, and verifiable example](http://stackoverflow.com/help/mcve), as well as this post on [creating a great example in R](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). Perhaps the following tips on [asking a good question](http://stackoverflow.com/help/how-to-ask) may also be worth a read. – lmo Mar 28 '17 at 11:15
  • `I've tried a for loop and also looked at apply but so far unsuccessfully.` - please share even if it didn't work. – zx8754 Mar 28 '17 at 11:22
  • 1
    `d <- 1:5; r <- 11:15; outer(d,r, FUN=function(d,r) 1+r/d)` or `1 + matrix(r, 5, 5, byrow=TRUE)/matrix(d, 5, 5)` – jogo Mar 28 '17 at 11:22
  • Thanks to everyone for pointing me to 'outer' – Lasse Tor Nielsen Mar 28 '17 at 11:34

2 Answers2

3

This should do it. define your function first. Then apply it with outer as suggested in the comments. Nice catch!

d <- 1:10
t <- 1:10
fun1 <- function(d,t){ (d + t ) / d }
outer(d, t, fun1)
OB83
  • 476
  • 2
  • 10
0

Here are three solutions:

d <- 1:5; r <- 11:15
outer(d,r, FUN=function(d,r) 1+r/d)
1 + matrix(r, 5, 5, byrow=TRUE)/matrix(d, 5, 5)
sapply(r, function(rr) 1 + rr/d)

and here is the result from benchmarking (+ additional solutions):

library("microbenchmark")
d <- 1:5; r <- 11:15
microbenchmark(
o= outer(d,r, FUN=function(d,r) 1+r/d),
o2= outer(d,r, FUN=function(d,r) (d+r)/d),
m= 1 + matrix(r, 5, 5, byrow=TRUE)/matrix(d, 5, 5),
m2= 1 + matrix(r, 5, 5, byrow=TRUE)/d,
s= sapply(r, function(rr) 1 + rr/d),
a= apply(as.matrix(r, 1), 1, function(rr) 1 + rr/d),
t= 1 + tcrossprod(1/d, r))
# Unit: nanoseconds
# expr   min      lq     mean  median      uq   max neval   cld
#    o  4497  5320.5  6423.44  6105.5  6659.5 15676   100   c  
#   o2  4392  5233.5  6591.64  6076.0  6681.0 18743   100   c  
#    m  2865  3468.0  4082.88  3783.0  4160.5 13109   100  b   
#   m2  1698  2196.5  2461.73  2349.5  2645.0  7715   100 a    
#    s 15602 17748.0 20496.18 19029.0 20770.5 53250   100    d 
#    a 26887 28836.5 32818.68 30272.5 35822.5 63613   100     e
#    t   990  1437.5  1796.66  1611.5  1770.5 10153   100 a  
jogo
  • 12,469
  • 11
  • 37
  • 42