Hello everyone, I have a vector P and I want to replace each of its missing values by its next element, for example: P[i] = NA --> P[i] = P[i+1] To do this I am using the replace() and lag() functions like this: P <- replace(as.ts(P),is.na(as.ts(P)),as.ts(lag(P,1))) but here is the error that I get: Warning message: In NextMethod("[<-") : number of items to replace is not a multiple of replacement length I have tried to reduce the dimension of P on the first two elements of the replace() function by one but it wouldn't work either. Any idea? ----- Anna Lippel -- View this message in context: http://n4.nabble.com/Error-on-using-lag-function-tp1399935p1399935.html Sent from the R help mailing list archive at Nabble.com.
Does this help: library(zoo) na.locf(P, fromLast=TRUE) You'll have to decide what to do if the last value is NA. -Peter Ehlers anna wrote:> Hello everyone, I have a vector P and I want to replace each of its missing > values by its next element, for example: > P[i] = NA --> P[i] = P[i+1] > To do this I am using the replace() and lag() functions like this: > P <- replace(as.ts(P),is.na(as.ts(P)),as.ts(lag(P,1))) > but here is the error that I get: > Warning message: > In NextMethod("[<-") : > number of items to replace is not a multiple of replacement length > I have tried to reduce the dimension of P on the first two elements of the > replace() function by one but it wouldn't work either. Any idea? > > ----- > Anna Lippel-- Peter Ehlers University of Calgary
anna wrote:> > Hello everyone, I have a vector P and I want to replace each of its > missing values by its next element, for example: > P[i] = NA --> P[i] = P[i+1] >You can also try P[which(is.na(P))]<- P[which(is.na(P))+1] or avoiding duplicate calculations index.Pna<-which(is.na(P)) P[index.Pna] <- P[index.Pna+1] You are left with having to decide what to do if the last element of P is NA. Berend -- View this message in context: http://n4.nabble.com/Error-on-using-lag-function-tp1399935p1415529.html Sent from the R help mailing list archive at Nabble.com.