How to write R for loops w/ variable value replacement -
question:
v vector multiple nas. write function replace these na values such missing value @ index should replaced mean of non-na values @ index p , q |p – i| + |q – i| minimized.
so, if vector ("na", 1, 2, "na", "na", 3)
result needs (1.5, 1, 2, 1.5, 1.5, 3)
how can write nested loop produce output?
you can use one:
vect <- c( na, 1, 2, na, na, 3) flag <- is.na(vect)+0 wh <- which(is.na(vect)==1) flag[flag==1] <- wh #flag container of values, missing vector position contain value of 0 non missing value contain position k <- 0 #a rolling itertor changes mean per non missing values in vector vect_ <- vect # final vector have outcome. for(i in 1:(length(vect))){ k <- ifelse(flag[i] > 0 , k+1,k) k <- ifelse(k == length(wh), k-1,k) vect_[i] <- ifelse(flag[i] > 0, mean(vect[min(wh):diff(c(1,wh[1+k]))],na.rm=t),vect[i] ) } vect_ > vect_ [1] 1.5 1.0 2.0 1.5 1.5 3.0
Comments
Post a Comment