Home > Blockchain >  How to use data.table fifelse function correctly in R?
How to use data.table fifelse function correctly in R?

Time:11-02

I have the following dataset that I am working with

dt <- data.table(RequestTime = c("2011-01-01 07:00:42","2011-01-02 05:00:47","2011-01-03 07:05:02","2011-01-04 04:00:42","2011-01-05 02:00:11"), ExportTime = c("2011-01-01 07:00:50","2011-01-05 05:00:52","2011-01-01 07:06:33","2011-03-04 04:00:51","2011-01-06 02:00:22"))

Since I am working with dates, converted both columns to the correct format using:

dt$RequestTime <- as.POSIXct(dt$RequestTime)
dt$ExportTime <- as.POSIXct(dt$ExportTime)

I am trying to use ifelse conditional statement to update the value of ExportTime based on the condition if the difference between the start date and the RequestTime is less than 86400 secs (24 hrs) then I keep ExportTime the same, but if the difference is greater than 86400 seconds, then the 2nd condition applies. Here is how I go about it.

x <- dt$RequestTime
y <- dt$ExportTime
start_date <- as.Date("2011-01-01")

dt$ExportTime <- fifelse((difftime(start_date, x, units = "secs") < 86400), y, 
    y - (difftime(start_date, x, units = "secs")))

So in this case, only the 1 out of the 5 observations should remain the same. But when I run this, I am seeing that all the observations stay the same. Any help would be appreciated)

CodePudding user response:

The reason is that the arguments should be switched or else all of them becomes negative

> difftime(start_date, x, units = "secs")
Time differences in secs
[1]  -46842 -126047 -219902 -295242 -374411
> difftime(start_date, x, units = "secs") < 86400
[1] TRUE TRUE TRUE TRUE TRUE
> difftime(x, start_date, units = "secs") < 86400
[1]  TRUE FALSE FALSE FALSE FALSE

i.e.

dt$ExportTime <- fifelse((difftime( x, start_date, units = "secs") < 86400), y, 
    y - (difftime(start_date, x, units = "secs")))

-output

> dt
           RequestTime          ExportTime
1: 2011-01-01 07:00:42 2011-01-01 07:00:50
2: 2011-01-02 05:00:47 2011-01-06 16:01:39
3: 2011-01-03 07:05:02 2011-01-03 20:11:35
4: 2011-01-04 04:00:42 2011-03-07 14:01:33
5: 2011-01-05 02:00:11 2011-01-10 10:00:33

Compare with the original

> dt
  RequestTime          ExportTime
1: 2011-01-01 07:00:42 2011-01-01 07:00:50
2: 2011-01-02 05:00:47 2011-01-05 05:00:52
3: 2011-01-03 07:05:02 2011-01-01 07:06:33
4: 2011-01-04 04:00:42 2011-03-04 04:00:51
5: 2011-01-05 02:00:11 2011-01-06 02:00:22
  • Related