R - Why is ifelse not working when comparing datetime hours that are less than 10?

56 views Asked by At

I am very new to R and I'm attempting to add a column (Time.Of.Day) to a dataframe (ny) where the values in the new column (Time.Of.Day) are based on the values of the hour of a timestamp (Start.Hour).

What I want to happen is: If Start.Hour is greater than 8 return "yes" otherwise return "no". I am not getting the expected answers. All results are returning "no" even when the Start.Hour is greater than 8 (like 14, 15, etc.).

Here is a screenshot of the code and results:

enter image description here

Here is the code I'm using and a truncated version of the resulting table when I call head(ny) afterwards (truncated table excluding all columns not related to Time.Of.Day):

ny$Time.Of.Day <- ifelse(ny$Start.Hour > 8,"yes","no")
head(ny)
Start.Time Start.Hour Time.Of.Day
2017-06-11 14:55:05 14 no
2017-05-11 15:30:11 15 no
2017-03-29 13:26:26 13 no
2017-05-08 19:47:18 19 no
2017-06-21 07:49:16 07 no
2017-02-22 18:55:24 18 no

If, however, I change it to greater than 10 instead of 8, then I receive the expected answers.

Here is a screenshot of the updated code and results:

enter image description here

Here is the updated code I'm using (where 8 is changed to 10) and a truncated version of the resulting table when I call head(ny) afterwards (truncated table excluding all columns not related to Time.Of.Day):

ny$Time.Of.Day <- ifelse(ny$Start.Hour > 10,"yes","no")
Start.Time Start.Hour Time.Of.Day
2017-06-11 14:55:05 14 yes
2017-05-11 15:30:11 15 yes
2017-03-29 13:26:26 13 yes
2017-05-08 19:47:18 19 yes
2017-06-21 07:49:16 07 no
2017-02-22 18:55:24 18 yes

The same unexpected results happen (all Time.Of.Day column values are no) whenever I'm comparing the Start.Hour value to any number less than 10 (9, 8, 7, etc.) and the expected results (correct yes and no values) happen whenever I'm comparing the Start.Hour value to any number greater than or equal to 10 (10, 11, 12, 13, etc.).

Am I missing something when it comes to comparing datetime hours that are less than 10?

For clarity, the Start.Hour column is the datetime value (from the Start.Time column) formatted to hours. I added in the Start.Hour column and populated it by using the below code:

ny$Start.Hour <- format(as.POSIXct(ny$Start.Time),format="%H")

I have also tried the below but getting the exact same result that all rows are "no"

ny$Time.Of.Day <- "no"
ny$Time.Of.Day[ny$Start.Hour > 8] <- "yes"
0

There are 0 answers