Sample data

```
set.seed(123)
df <- data.frame(year = c(rep(1980:1994, each = 9), rep(1995, times = 8), rep(1996:2012, each = 9), 
                          rep(2013, times = 7), rep(2014, times = 9)),
                 ref.doy = sample(120:180, 312, replace = T),
                 x = rnorm(312))

```

For each year, if no. of `ref.doy` is not 9, then I want to insert additional new rows which is the just the copy of the last row.

For e.g. if for 1995, there are only 8 `ref.doy`, I want to copy the 8th row make it 9th row. If 2013, there are only 8 `ref.doy`, then I want to copy the 7th row and duplicate it as 8th and 9th row and so on.

The solution I have at the moment is a for-loop:

```
x <- df %>% group_by(year) %>% dplyr::mutate(y.length = n())
year.vec <- 1980:2014
temp.list <- list()

for(y in seq_along(year.vec)){

  yr <- year.vec[y]
  temp <- x %>% dplyr::filter(year == yr)  

  if(unique(temp$y.length) != 9) {

    lastrow <- temp[nrow(temp), ]
    lastrow.repeat <- as.data.frame(lapply(lastrow, rep, 9 - nrow(temp))) 
    full.data  <- rbind(data.frame(temp), lastrow.repeat)         
    temp.list[[y]] <- full.data

    } else {
    temp.list[[y]] <- temp
  }
}

newdata <- rbindlist(temp.list)

```

I need some help to do it within `dplyr` or `data.table` itself.