Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare time in R

Tags:

timestamp

time

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?

like image 341
darkage Avatar asked Dec 02 '25 00:12

darkage


1 Answers

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.

like image 174
G. Grothendieck Avatar answered Dec 03 '25 15:12

G. Grothendieck



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!