Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subset rows according to a range of time

Tags:

time

r

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 
like image 483
Wet Feet Avatar asked Oct 17 '13 06:10

Wet Feet


People also ask

What is subset of rows?

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.

How do you subset a range in R?

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)].

How do you subset a row in a Dataframe?

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.


1 Answers

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,]
like image 65
juba Avatar answered Oct 08 '22 23:10

juba