0

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?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • Maybe group by `month` and then use `group_split()`. It would be easier to test with a proper [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input in `dput()` form and the desired output that can be used to test and verify possible solutions. – MrFlick Dec 24 '20 at 00:48
  • @MrFlick i always miss the right template. thx for calling my attention. i will commit more in the nxt time. I still familiarizing w the platform hehe – Caio Scaravajar Dec 24 '20 at 01:48

2 Answers2

1

An option is to convert to yearmon class from zoo

library(zoo)
library(dplyr)
out <- df %>%
    group_split(grp = as.yearmon(col1), .keep = FALSE)
akrun
  • 874,273
  • 37
  • 540
  • 662
0

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'))
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213