Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to extract the hour component in R

I have following code and as you can see system calculating the difference correctly, but I would like consider only first 5 character i.e. 3.449 etc and I like to discard the ‘hours’ part.
Once I try to convert the same as character, then it not working.
Any help will be appreciated.

library(dplyr)

df %>%
  mutate(difference = difftime(DateTime_Stat, DateTime_End, units = 'hours'))

#       DateTime_Start        DateTime_End     difference
#1 2021-02-02 16:42:11 2021-02-02 16:43:15 0.000000 hours
#2 2021-02-02 20:10:14 2021-02-02 20:11:55 3.449754 hours

I have tried to convert the value to character type so I can use substr() to extract the values but system is failing to convert it to as character.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can convert to numeric and round:

round(as.numeric(df$difference), 3)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading