mercredi 5 juin 2019

Is there a faster way of creating a new vector by comparing 4 other vectors through rows i and i-1, in R?

   h <- vector( "integer", length = length(Data[,1]))
   f <- function(x, y, z, q){
         for( i in 1:length(x)){
             if (identical(z[i],y[i]))  h[i] <- 1
             else if ( identical (x[i], x[i-1]) && (z[i] <= q[i])) 
                      h[i] <-as.integer(h[i-1]+1)
             h[i] <- "" }
          return(h)
          }  

as_tibble(Data)  # just to illustrate the dataset
Data <- mutate(Data, New_Col = f(Col_1, Col_2, Col_3, Col_4))

This works but slowly, it took: 116.536000 seconds

Aucun commentaire:

Enregistrer un commentaire