fast way in R to do two nested for loops

Viewed 1502

I need to take the difference between any two elements of two vector. If A<-c(1,2) and B<-c(3,4) then my result R should be c(3-1,3-2,4-1,4-2).

With this snippet

myfunction <- function(N)
{
  A = runif(N)
  B = runif(N)
  R = c()
  for(a in A){
    for(b in B){
      R=c(b-a,R)
    }
  }
  R
}
print(system.time(result <- myfunction(300)))

I get this time

   user  system elapsed 
  14.27    0.01   14.39 

Is there any faster way to do it?

3 Answers
Related