darkage
darkage

Reputation: 857

Compare time in R

I have two columns, say A and B (time in HH:MM format)

  A       B
00:00   06:00

str(A) and str(B) gives "character."

I want to make a comparison like,e.g.,

Comment <- ifelse(hour_part(A) < hour_part(B), "Dead","NONE")

I want to do it in R.

How can this be done in R?

Upvotes: 3

Views: 15207

Answers (3)

Rich Scriven
Rich Scriven

Reputation: 99391

Similar to Christian's answer, only using difftime,

ifelse(difftime(A, B) < 0, "Dead", "None")
# [1] "Dead"

Data:

A <- strptime("00:00", "%H:%M")
B <- strptime("06:00", "%H:%M")

Upvotes: 4

G. Grothendieck
G. Grothendieck

Reputation: 270348

Using this test data:

DF <- data.frame(A = "00:00", B = "06:00", stringsAsFactors = FALSE) # test data

1) character class This works with the original character representation:

hour_part <- function(x) as.numeric(sub(":.*", "", x)) # can optionally omit as.numeric
Comment <- ifelse(hour_part(DF$A) < hour_part(DF$B), "Dead", "NONE")

2) times class If this is not the only thing you want to do with DF then it might be better to first convert them to "times" class.

library(chron)

to.times <- function(x) times(paste0(x, ":00"))
DF2 <- transform(DF, A = to.times(A), B = to.times(B))
Comment <- ifelse(hours(DF2$A) < hours(DF2$B), "Dead", "NONE")

Note: Next time please provide the test data in reproducible form.

Upvotes: 5

Christian Borck
Christian Borck

Reputation: 1862

Try

ifelse(strptime(A, "%H:%M") < strptime(B, "%H:%M"), "Dead", "NONE")

(Note that this solution converts the hours and minutes into today's datetime)

Upvotes: 4

Related Questions