You can avoid the loop or the apply statement by vectorizing the ifelse statement. If you define i as the vector from 3:length(E$phone), you can then run the ifelse statement directly. #test data phone<-c(123,123,123,333,333,333,456,456,456,789,789,789,500,500,500) time<-c(“2018-11-06″,”2018-11-06″,”2018-11-06″,”2018-11-09″,”2018-11-09″,”2018-11-09”, “2018-11-07″,”2018-11-07″,”2018-11-07″,”2018-11-05″,”2018-11-05”, “2018-11-05”, “2018-11-06″,”2018-11-06″,”2018-11-06”) time<-as.Date(time) tel<-c(0,0,1,1,0,1,1,1,0,1,1,1,0,0,1)…