tidyverse / hms

A simple class for storing time-of-day values
https://hms.tidyverse.org/
Other
138 stars 25 forks source link

is hms similar to between_time in Pandas? #27

Closed randomgambit closed 7 years ago

randomgambit commented 7 years ago

Hello there!

I am wondering is one can use this package to slice a dataframe according to the time in the day.

I am looking for something similar to Pandas' between_time (http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.between_time.html)

If so, that would be very useful because there is no function to do cleanly that in R, except by converting the time into a string such as 05:00:02 and performing string-based comparisons (which can be error prone) like filter(time_str > "08:00:00")

Thanks!

ellisvalentiner commented 7 years ago

You can likely use hms for this but is very straightforward using dplyr and lubridate.

mydata %>%
  filter(hour(datetimevar) > 8)
randomgambit commented 7 years ago

@ellisvalentiner a-ha! unfortunately it is not that simple..

Try to filter a dataframe between 19:59 and 22:38 using your technique for instance... This becomes super ugly pretty quick. This is why between_time in Pandas is so useful. Maybe you can do something similar here?

ellisvalentiner commented 7 years ago

Sure, it is the same idea:

# Sample data for reproducible example
mydata <- data.frame(
  datetimevar = seq(
    from = as.POSIXct("2017-04-13 00:00:00"),
    to = as.POSIXct("2017-04-14 00:00:00"),
    by = 1))

mydata %>%
  # Extract just the time component
  mutate(
    just_time = as.hms(strftime(datetimevar, format = "%T"))
  ) %>%
  # Then filter or slice as you normally would
  filter(just_time > as.hms("19:59:00") & just_time < as.hms("22:38:00"))
randomgambit commented 7 years ago

sweet

randomgambit commented 7 years ago

@ellisvalentiner can we install this package without devtools? On my machine at work, I cannot install rtools....

ellisvalentiner commented 7 years ago

The package is available on CRAN: https://cran.r-project.org/web/packages/hms/

github-actions[bot] commented 3 years ago

This old thread has been automatically locked. If you think you have found something related to this, please open a new issue and link to this old issue if necessary.