使用ifelse在多个条件下编程R

时间:2018-12-04 15:08:52

标签: r conditional-statements

你帮我。

我有四个列的data.frame E 我在R中仅使用基本软件包 我不使用for循环 我有百万行

phone<-c(123,123,123,333,333,333,456,456,456,789,789,789,500,500,500,....etc) 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...etc) 
tel<-c(0,0,1,1,0,1,1,1,0,1,1,1,0,0,1,...etc)       
porad<-c(1,2,3,1,2,3,1,2,3,1,2,3,1,2,3....etc)

我想用结果创建新列

E$de<-c(0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,...etc)

所以我使用了循环,整个过程大概运行了4个小时。

E$de[1]=ifelse(E$phone[i]==E$phone[i+1] & E$time[i]==E$time[i+1] & E$porad[1]==2 & E$tel[1]==1,1,0)
E$de[2]=ifelse(E$phone[i]==E$phone[i+1] & E$time[i]==E$time[i+1] & E$porad[2]==3 & E$tel[2]==1,1,0)
for (i in 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)
}

请帮助我:D

1 个答案:

答案 0 :(得分:5)

通过向量化ifelse语句,可以避免循环或apply语句。

如果您将i定义为3:length(E $ phone)中的向量,则可以直接运行ifelse语句。

#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)

这应该比for循环快大约1000倍。