I used the following code to turn each i-th NA in the variable x into the (i-1)-th value of the variable x and it works fine but it takes too much time, since the dataset is large.
for (i in 2:nrow(data_final)) {
data_final$COD_ATC5[i] <- ifelse(is.na(data_final$COD_ATC5[i]), data_final$COD_ATC5[i-1], data_final$COD_ATC5[i])
}
Do you have other faster idea?
Here a reproducible example of the dataset:
data_final <- data.frame(ID=c(rep("01",12),rep("02",12)), t = rep(1:12,2), x= c(rep("A",4),NA,rep("A",3),rep("C",4),rep("A",5),rep("C",3),NA,"C",rep("A",2)))