简体   繁体   English

使用具有多个条件的 ifelse 编程 R

[英]programming R using ifelse with multiple conditions

an you help me .一个你帮我。

i have data.frame E with four columns i use only basic package in R i do not use for- loop i have milion rows我有四列的 data.frame E 我只在 R 中使用基本包我不使用 for-loop 我有一百万行

 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)

i want to create new columns with results我想用结果创建新列

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

so i used loop and the process ran probably 4 hours.所以我使用了循环,这个过程可能运行了 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)
}

please help me :D请帮帮我:D

You can avoid the loop or the apply statement by vectorizing the ifelse statement.您可以通过向量化ifelse语句来避免循环或 apply 语句。

If you define i as the vector from 3:length(E$phone), you can then run the ifelse statement directly.如果将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)

This should run approximately 1000x faster than the for loop.这应该比 for 循环快大约 1000 倍。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM