r - efficient vectorizisation of a double for loop -
how can 1 vectorize following double loop in r?
a <- seq(1,10, length=5) b <- seq(0,1, length=4) fun <- function(a,b){return(a+b)} out <- matrix(nan, nrow=5, ncol=4) for(i in 1:5) { for(j in 1:4) { out[i, j] <- fun(a[i], b[j]) } }
i have attempted, example, without success. please advise, in advance
outer(1:nrow(out), 1:ncol(out), fun = fun(a,b)) mapply(out, fun)
what about:
outer(a, b, '+') ## > outer(a, b, '+') ## [,1] [,2] [,3] [,4] ## [1,] 1.00 1.333333 1.666667 2.00 ## [2,] 3.25 3.583333 3.916667 4.25 ## [3,] 5.50 5.833333 6.166667 6.50 ## [4,] 7.75 8.083333 8.416667 8.75 ## [5,] 10.00 10.333333 10.666667 11.00
Comments
Post a Comment