df <- data.frame(a = c(1:5, "", 3, "", "", "", 4), stringsAsFactors = FALSE)
> df
a
1 1
2 2
3 3
4 4
5 5
6
7 3
8
9
10
11 4
while(length(ind <- which(df$a == "")) > 0){
df$a[ind] <- df$a[ind -1]
}
> df
a
1 1
2 2
3 3
4 4
5 5
6 5
7 3
8 3
9 3
10 3
11 4
EDIT:
set.seed(1)
N = 1e6
df <- data.frame(a = sample(c("",1,2),size=N,replace=TRUE),
stringsAsFactors = FALSE)
if(df$a[1] == "") {df$a[1] <- NA}
system.time(
while(length(ind <- which(df$a == "")) > 0){
df$a[ind] <- df$a[ind - 1]
}, gcFirst = TRUE)
user system elapsed
0.89 0.00 0.88