I have vectors with mostly NA entries. I want to replace every NA with that vector's preceding non-NA entry. Specifically, the first entry will always be a 1, followed by a bunch of NAs, which I want to replace with 1. The ith entry could be another numeric, let's say 2, followed by more NAs that I want to replace with 2. And so on. The loop below achieves this, but there has to be a more R way to do it, right? I wanted to vectorize with ifelse(), but I couldn't figure out how to replace the ith entry with the i-1th entry.
> vec <- rep(NA, 10)
> vec
[1] NA NA NA NA NA NA NA NA NA NA
> vec[1] <- 1; vec[4] <- 2; vec[7] <- 3
> vec
[1] 1 NA NA 2 NA NA 3 NA NA NA
> for (i in 1:length(vec)) if (is.na(vec[i])) vec[i] <- vec[i-1]
> vec
[1] 1 1 1 2 2 2 3 3 3 3
Thanks!
If context helps, I am adjusting for stock splits from the WRDS database, which has a column that shows when and how a split occurs.