[Solved] programming R using ifelse with multiple conditions


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] & E$porad[2]==3 & E$tel[2]==1,1,0)

#vectorized ifelse statement
i<-3:length(E$phone)
E$de[i]<-ifelse(E$phone[i]==E$phone[i-2] & E$time[i]==E$time[i-2] & E$porad[i]==3 & E$tel[i]==1 & E$tel[i-1]==0 & E$tel[i-2]==0,1,0)

This should run approximately 1000x faster than the for loop.

0

solved programming R using ifelse with multiple conditions