r - How to calculate matrix based on two vectors -


i'm sure simple one. have 2 vectors 'd' , 'r'. calculate t=(d+r)/d combinations of d , r. thus, end matrix t calculated each d using each value of r.

output should this: https://www.dropbox.com/s/hf74s4jz2qe3st7/table.jpg?dl=0

i've tried for loop , looked @ apply far unsuccessfully.

i hope can help.

edit: for loop tried:

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

didn't work :(

here 3 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 result 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     #    s 15602 17748.0 20496.18 19029.0 20770.5 53250   100    d  #    26887 28836.5 32818.68 30272.5 35822.5 63613   100     e #    t   990  1437.5  1796.66  1611.5  1770.5 10153   100   

Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -