I'm trying to impute NA
's of temperature data in R. It is spatiotemporal data which has 487 observatories and 60 time units (60 months).
What I want to do here is replace NA
with the value of which has the smallest distance (not zero) from the NA
's observatory in the same month.
Here is my R code (temp_1 is the name of my data).
pos.min = function(v){ # find positive minimum index
v.na = v
v.na[v==0] = NA
return(which.min(v.na))
}
for (i in 1:60){
for (j in 1:sum(is.na(temp_1[i,]))){
na.index=which(is.na(temp_1[i,]))
dz.index=pos.min(dz[na.index[j],])
new=temp_1[i,dz.index]
temp_1[i,][is.na(temp_1[i,])][j]=new
}
}
However, when I run this I get an error message
Error in temp_1[i, ][is.na(temp_1[i, ])][j] = new : replacement has length zero
I typed class(new)
and it says data.frame, so I've changed it into numeric by new=as.numeric(temp_1[i,dz.inex])
. But it comes to the same error.
I don't understand why I get this error message... I appreciate your help a lot.