Replace double for double lapply

0

I am trying to replace my code that has double for one with double lapply in order to optimize the program since r works in matrix form, it works like this:

k<-1
for(i in 1:nrow(tab1)){
   for(j in 1:nrow(tab2)){


      tab3$col1[k]<-tab1$col1[i]
      tab3$col2[k]<-tab2$col3[j]
      k<-k+1

    }

  }

I would like it to stay that way, but I do not know how to do it can help? Thanks

lapply(1:nrow(tab1),fuction(i){
  lapply(1:nrow(tab2), function(j){

   ??????????

  })
})
    
asked by anonymous 13.04.2018 / 22:42

1 answer

1

Hello

Actually, apply's can be slower than loops, if in the loop you take care to pre-allocate your vector.

As for your problem, it looks like you want to make all combinations of tab1 $ col1 and tab2 $ col3.

I suggest using expand.grid() :

tab3 <- expand.grid(col1 = tab1$col1, col2 = tab2$col3)

The order will be different, but this is easily solved with order() .

A hug!

    
02.06.2018 / 00:07