Grouped Seq of Dates by Month

Hello,

I have a data frame with multiple IDs, I'm trying to write a code which will sequence out by column BDate and grouped by ID. For Example, ID A's BDate is equal to 2014-01-27 so the next row will be 2014-02-27 followed by 2014-03-27...etc.

I tried using the sequence function seq but I get this error Error in seq.Date(as.Date(BDate), by = "month", length.out = Span) : 'from' must be of length 1

Any ideas on how I can properly get this sequence to execute?

df<-data.frame(ID=c("A","B"),BDate=c("2014-01-27","2014-03-31"),Span=c(10,10))
df <- df[rep(row.names(df), df$Span),]
df2<-df%>%group_by(ID)%>%mutate(PDate=seq(as.Date(BDate), by = "month", length.out =Span ))


Is this what you are looking for?

df<-data.frame(ID=c("A","B"),BDate=c("2014-01-27","2014-03-31"),Span=c(10,10))
df <- df[rep(row.names(df), df$Span),]
library(lubridate)
#> 
#> Attaching package: 'lubridate'
#> The following objects are masked from 'package:base':
#> 
#>     date, intersect, setdiff, union
library(dplyr, warn.conflicts = FALSE)

df %>% group_by(ID) %>% mutate(PDate = as.Date(min(BDate)) %m+% months(0:(min(Span)-1)))
#> # A tibble: 20 x 4
#> # Groups:   ID [2]
#>    ID    BDate       Span PDate     
#>    <chr> <chr>      <dbl> <date>    
#>  1 A     2014-01-27    10 2014-01-27
#>  2 A     2014-01-27    10 2014-02-27
#>  3 A     2014-01-27    10 2014-03-27
#>  4 A     2014-01-27    10 2014-04-27
#>  5 A     2014-01-27    10 2014-05-27
#>  6 A     2014-01-27    10 2014-06-27
#>  7 A     2014-01-27    10 2014-07-27
#>  8 A     2014-01-27    10 2014-08-27
#>  9 A     2014-01-27    10 2014-09-27
#> 10 A     2014-01-27    10 2014-10-27
#> 11 B     2014-03-31    10 2014-03-31
#> 12 B     2014-03-31    10 2014-04-30
#> 13 B     2014-03-31    10 2014-05-31
#> 14 B     2014-03-31    10 2014-06-30
#> 15 B     2014-03-31    10 2014-07-31
#> 16 B     2014-03-31    10 2014-08-31
#> 17 B     2014-03-31    10 2014-09-30
#> 18 B     2014-03-31    10 2014-10-31
#> 19 B     2014-03-31    10 2014-11-30
#> 20 B     2014-03-31    10 2014-12-31

Created on 2021-03-09 by the reprex package (v0.3.0)

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.