Pushok

R replace NA with MA

May 31st, 2016
350
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 0.50 KB | None | 0 0
  1. replaceWithMA <- function(x) {
  2.   for(i in 1:length(x)){
  3.     if(is.na(x[i])){
  4.       start <- i
  5.       while(is.na(x[i]) & i < length(x)) i <- i + 1
  6.       if(start == 1 & i <= length(x)){
  7.         for(j in start:i){
  8.           x[j] <- x[i]
  9.         }
  10.       }
  11.       else if(i < length(x)) {
  12.         for(j in start:(i-1)){
  13.           x[j] <- ma
  14.         }
  15.       }
  16.       else if(i == length(x)){
  17.         for(j in start:i){
  18.           x[j] <- x[start-1]
  19.         }
  20.       }
  21.     }
  22.   }
  23.  
  24.   return(x)
  25. }
Advertisement
Add Comment
Please, Sign In to add comment