Search code examples
rdataframeslicerows

How do I slice rows based in a global criteria?


I'm struggling to slice my rows based in a global criteria. I have a df like this:

         col1           col2            col3
 1. 2020-10-31 
 2. 2020-10-30 
 3. 2020-10-29 
 4. 2020-10-28
....
 43. 2020-9-30 
 44. 2020-9-29 
 45. 2020-9-28 
 46. 2020-9-27 

And so on... Basically, each row at the first column contain a specific date (y/m/d) and it is decreasing. I'm using the slice() function to break the df based on a month-by-month approach (and creating new dfs separated by months). So, what I do is identify in which row the month begins and in which one it ends, then I do something like this:

  dfnovember <- df %>%    
                  slice(1:46)

With it, I get what I need, but is tough (very manual). I would like to know if there's a different function where I can apply the criteria (month-by-month) and get all of it with one putt. Something like (pseudo function):

dfgenericmonth <- df %>%    
               slice(month[day 31 to 01])

Can anybody help me?


Solution

  • You can extract the month out from col1 and use it in split to split data into list of dataframes, one for each month.

    result <- split(df, format(as.Date(df$col1), '%Y-%m'))