Home > Back-end >  How to apply `filter`, `ifelse` and `mutate` in `hms` data in R
How to apply `filter`, `ifelse` and `mutate` in `hms` data in R

Time:08-18

I have a hms data for appointment dates. Here is the sample data:

library(hms)
library(dplyr)
dput(SampleData[1:5,])

structure(list(AppointmentDate = structure(c(1634097600, 1600228800, 
1603080000, 1604552400, 1606107600), class = c("POSIXct", "POSIXt"
), tzone = ""), AppointmentTime = structure(c(5400, 28800, 28800, 
28800, 28800), class = c("hms", "difftime"), units = "secs"), 
CheckinTime = structure(c(48060, 29460, 28740, 28800, 29160
), class = c("hms", "difftime"), units = "secs")), row.names = c(NA, 
5L), class = "data.frame")

There is a typo in the AppointmentTime (it is obvious from the CheckinTime). I want to detect and change it using ifelse and mutate in R. I tried using the following code but, it turns AppointmentTime column to numbers.

RawData %>%
  mutate(AppointmentTime = ifelse(AppointmentTime == parse_hms("01:30:00"), parse_hms("13:30:00"), as_hms(AppointmentTime))) 

I want the following result.

  AppointmentDate AppointmentTime CheckinTime
1      2021-10-13        13:30:00    13:21:00
2      2020-09-16        08:00:00    08:11:00
3      2020-10-19        08:00:00    07:59:00
4      2020-11-05        08:00:00    08:00:00
5      2020-11-23        08:00:00    08:06:00

CodePudding user response:

It is a known issue of type coersion with ifelse as it coerces to its storage mode which is numeric

> str(parse_hms("01:30:00"))
 'hms' num 01:30:00
 - attr(*, "units")= chr "secs"
> mode(parse_hms('01:30:00'))
[1] "numeric"
> as.numeric(parse_hms("01:30:00"))
[1] 5400

use case_when or if_else which would check the types and return accordingly

library(hms)
library(dplyr)
RawData %>%
  mutate(AppointmentTime = if_else(AppointmentTime == parse_hms("01:30:00"), 
      parse_hms("13:30:00"), as_hms(AppointmentTime)))

-output

 AppointmentDate AppointmentTime CheckinTime
1      2021-10-13        13:30:00    13:21:00
2      2020-09-16        08:00:00    08:11:00
3      2020-10-19        08:00:00    07:59:00
4      2020-11-05        08:00:00    08:00:00
5      2020-11-23        08:00:00    08:06:00
  • Related