Closed randomgambit closed 7 years ago
You can likely use hms
for this but is very straightforward using dplyr
and lubridate
.
mydata %>%
filter(hour(datetimevar) > 8)
@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?
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"))
sweet
@ellisvalentiner can we install this package without devtools
? On my machine at work, I cannot install rtools....
The package is available on CRAN: https://cran.r-project.org/web/packages/hms/
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.
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) likefilter(time_str > "08:00:00")
Thanks!