Search code examples
rloopslag

Replace NA with Value with Previous Value


I have a column in data frame that I created in R. After a certain month, the values become NA. I would like to replace the NAs with the record 12 months back. Is there a function in R for me to do this? Or do I have to do a loop?

So Jan-11 would then become 10, Feb-11 would become 11 and so forth.

EDIT:

I also tried:

for (i in 1:length(df$var)) { 
df$var[i] <- ifelse(is.na(df$var[i]), df$var[i - 12], 
df$var[i]) }

but the whole column ends up being NA.

enter image description here


Solution

  • I can't think of a way to do this without a loop, but this should give you what you need:

    df <- data.frame(col1 = LETTERS[1:24],
                 col2 = c(rnorm(12), rep(NA, 12)))
    for(i in 1:nrow(df)) {
        if(is.na(df[i, 2])) {
        df[i, 2] <- df[i - 12, 2]
      }
    }