Assign monthly date record for each Id from starting dates in a DF

Running this code should give you a vector consisting of what you want:

#Defining data
Id = c(00167,00167,00167,00168,00168,00168,00207,00207,00207)
Ctrl_num = c(1,2,3,1,2,3,1,2,3)
Ctrl_date = c('1988-10-15',NA,NA,'1990-02-15',NA,NA, '1988-11-15',NA,NA)
df = data.frame(Id, Ctrl_num, Ctrl_date)

#Finds index of known dates
ID = which(!$Ctrl_date))
#Finds needed length of sequence
d = diff(c(ID, length(df$Ctrl_date) + 1))

#Creates new date-vector
ctrl_date2 = as.Date(rep(NA,length(df$Ctrl_date)))
for(i in 1:length(ID)){
  ctrl_date2[ID[i]:(ID[i]+d[i]-1)] = seq(as.Date(df$Ctrl_date[ID[i]]), 
                                         by='30 day', length.out=d[i])

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top