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) porad<-c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3) E<-data.frame(phone, time, tel, porad) E$de[1]=ifelse(E$phone[1]==E$phone[2] & E$time[1]==E$time[2] & E$porad[1]==2 & E$tel[1]==1,1,0) E$de[2]=ifelse(E$phone[2]==E$phone[3] & E$time[2]==E$time[3] … Read more