Search code examples
rdatetimeif-statementposixct

Using an ifelse() statement for datetime observations within a given interval


I would like to assign a value to the df$lamp_intensity vector depending on a specific time interval within df$date. If a given observation is outside of this interval, I would like to assign an NA. Once I get this first bit of code working, I plan on nesting a bunch of ifelse() statements to handle multiple time intervals. I think I'm pretty close, but I could definitely use a hand.

Thank you!

Here's my data:

df <- structure(list(date = structure(c(1504787028, 1504787030, 1504787031, 1504787032, 1504787033, 1504787034, 1504787035, 1504787036, 1504787037, 1504787038), class = c("POSIXct", "POSIXt"), tzone = "UTC"), ppm = c(0.0009765625, 0.0009765625, 0.0009765625, 0.0009765625, 0.0009765625, 0.0009765625, 0.0009765625, 0.0009765625, 0.0009765625, 0.00146484375)), .Names = c("date", "ppm"), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"))

df$lamp_intensity <- ifelse(df$date >= as.POSIXct("2017-09-07 12:23:51",
    format = "%Y-%m-%d %H:%M:%S", tz = "UTC") && ## using '&' generates an error message
    date <= as.POSIXct("2017-09-07 12:23:55",
    format = "%Y-%m-%d %H:%M:%S", tz = "UTC"), 0, NA)

head(df, 10)

The solution would assign 0 for df$lamp_intensity rows between 2017-09-07 12:23:51 and 2017-09-07 12:23:55


Solution

  • You could use the cut function instead. For example:

    df$lamp_intensity = cut(df$date, 
                            breaks=as.POSIXct(c("2017-09-07 12:23:42","2017-09-07 12:23:55",
                                                "2017-09-07 12:24:02", "2017-09-07 12:24:31"), tz="UTC"),
                            labels=c(0,1,2))
    
                      date          ppm lamp_intensity
     1 2017-09-07 12:23:48 0.0009765625              0
     2 2017-09-07 12:23:50 0.0009765625              0
     3 2017-09-07 12:23:51 0.0009765625              0
     4 2017-09-07 12:23:52 0.0009765625              0
     5 2017-09-07 12:23:53 0.0009765625              0
     6 2017-09-07 12:23:54 0.0009765625              0
     7 2017-09-07 12:23:55 0.0009765625              1
     8 2017-09-07 12:23:56 0.0009765625              1
     9 2017-09-07 12:23:57 0.0009765625              1
    10 2017-09-07 12:23:58 0.0014648438              1