I have dated data frame like this one with approximately 1 million rows

```
  id       date   variable
1  1 2015-01-01         NA
2  1 2015-01-02 -1.1874087
3  1 2015-01-03 -0.5936396
4  1 2015-01-04 -0.6131957
5  1 2015-01-05  1.0291688
6  1 2015-01-06 -1.5810152

```

Reproducible example is here:

```
#create example data set
Df <- data.frame(id = factor(rep(1:3, each = 10)), 
     date = rep(seq.Date(from = as.Date('2015-01-01'), 
             to = as.Date('2015-01-10'), by = 1),3),
     variable = rnorm(30))
Df$variable[c(1,7,12,18,22,23,29)] <- NA

```

What I want to do is replace NA values in `variable` with values from previous date for each `id`. I created loop which works but very slow (You can find it below). Can you please advice fast alternative for this task. Thank you!

```
library(dplyr)

#create new variable
Df$variableNew <- Df$variable
#create row numbers vector
Df$n <- 1:dim(Df)[1]
#order data frame by date
Df <- arrange(Df, date)

for (id in levels(Df$id)){
    I <- Df$n[Df$id == id] # create vector of rows for specific id

    for (row in 1:length(I)){ #if variable == NA for the first date change it to mean value
        if (is.na(Df$variableNew[I[1]])) {
            Df$variableNew[I[row]] <- mean(Df$variable,na.rm = T)
        }
        if (is.na(Df$variableNew[I[row]])){ # if variable == NA fassign to this date value from previous date
            Df$variableNew[I[row]] <- Df$variableNew[I[row-1]]
        }
    }
}

```