kishore
kishore

Reputation: 187

giving if condition for time

Is there any way we can give a condition statement in a if else loop as

 a= "06/28/2017 08:45"
 b= "06/28/2017 08:32"
 c= difftime(a,b,units="mins)
`if(a+30 > b)
 { 
  print("you are late")
  }else
  print("on time")`

my data frame is

      col1                       col2
  6/27/2017 11:00 
  6/27/2017 20:45            
  6/24/2017 19:30               6/24/2017 18:48
  6/27/2017 20:00               6/28/2017 3:16
  6/29/2017 18:30               
  7/4/2017 7:30
  6/24/2017 1:30               6/24/2017 0:21
  6/29/2017 10:00
  6/28/2017 16:30              6/28/2017 18:39
  7/2/2017 19:00

I'm getting error as

 `1.Error in if (a+30 > b) missing value where TRUE/FALSE needed
  In Ops.factor(a+30 > b) :‘>’ not meaningful for factors
  2: In if (a+30 > b) { : the condition has length > 1 and only the first element will be used`

What I'm trying to do is to add 30min to 'a' and compare it wih 'b' to determine if something is late or on time.

Upvotes: 0

Views: 1783

Answers (3)

Ajay Ohri
Ajay Ohri

Reputation: 3492

library(lubridate)
a=mdy_hm("06/28/2017 08:45")
b=mdy_hm("06/28/2017 08:32")
c= abs(difftime(a,b,units="mins))
d=ifelse(30>c,"you are late","on time")
print(d)

Upvotes: 0

Edgar Santos
Edgar Santos

Reputation: 3514

How about:

library(lubridate)
library(dplyr)
a= mdy_hm("06/28/2017 08:20")
b= mdy_hm("06/28/2017 08:32")
if_else(a + minutes(30) > b, "you are late", "on time")

Upvotes: 1

Jan
Jan

Reputation: 4206

If you format your dates correctly and use a minus instead of a plus in the if statement, it works fine:

a= as.Date("06/28/2017 08:45", "%m/%d/%Y %H:%M")
b= as.Date("06/28/2017 08:32", "%m/%d/%Y %H:%M")

if(a-10 > b) { 
        print("you are late")
} else {
    print("on time")
}

Change the a-10 to a-30 and you will be late.

Upvotes: 2

Related Questions