I have a data frame that looks like that
date_time loc_id node energy kgco2
1 2009-02-27 00:11:08 87 103 0.00000 0.00000
2 2009-02-27 01:05:05 87 103 7.00000 3.75900
3 2009-02-27 02:05:05 87 103 6.40039 3.43701
4 2009-02-27 03:05:05 87 103 4.79883 2.57697
5 2009-02-27 04:05:05 87 103 4.10156 2.20254
6 2009-02-27 05:05:05 87 103 2.59961 1.39599
Is there anyway I can subset it according to range of time, for example, 2am to 5am. I should then get a result that looks like this:
date_time loc_id node energy kgco2
3 2009-02-27 02:05:05 87 103 6.40039 3.43701
4 2009-02-27 03:05:05 87 103 4.79883 2.57697
5 2009-02-27 04:05:05 87 103 4.10156 2.20254
A Row Subset is a selection of the rows within a whole table being viewed within the application, or equivalently a new table composed from some subset of its rows. You can define these and use them in several different ways; the usefulness comes from defining them in one context and using them in another.
table object using a range of values, we can use single square brackets and choose the range using %between%. For example, if we have a data. table object DT that contains a column x and the values in x ranges from 1 to 10 then we can subset DT for values between 3 to 8 by using the command DT[DT$x %between% c(3,8)].
To randomly select the specified number of rows from the data frame to subset, specify the random() function for the logical criterion of the rows . The value passed to random() can either be the actual number of rows to select, or the proportion of rows to select.
One way to do it is to use lubridate
and define an interval :
library(lubridate)
date1 <- as.POSIXct("2009-02-27 02:00:00")
date2 <- as.POSIXct("2009-02-27 05:00:00")
int <- new_interval(date1, date2)
df[df$datetime %within% int,]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With