Pushok icon

R replace NA with MA

Pushok | PRO | 05/31/16 07:13:46 AM UTC | 0 ⭐ | 339 👁️ | Never ⏰ | []
R |

500 B

|

None

|

0 👍

/

0 👎

replaceWithMA <- function(x) {
  for(i in 1:length(x)){
    if(is.na(x[i])){
      start <- i
      while(is.na(x[i]) & i < length(x)) i <- i + 1
      if(start == 1 & i <= length(x)){
        for(j in start:i){
          x[j] <- x[i]
        }
      }
      else if(i < length(x)) {
        for(j in start:(i-1)){
          x[j] <- ma
        }
      }
      else if(i == length(x)){
        for(j in start:i){
          x[j] <- x[start-1]
        }
      }
    }
  }
  
  return(x)
}

Comments