If I understand correctly what you want (according to your loop), you could use the na.locf function in pkg:zoo.
library(zoo) mat <- t(apply(mydata, 1, na.locf, fromLast=TRUE, na.rm=FALSE)) dat <- as.data.frame(mat) ## since apply returns a matrix -Peter Ehlers On 2010-04-05 10:52, Anna Stevenson wrote:
#I wish to find the "next non-NA" value within each row of a data-frame. #e.g. I have a data frame mydata. Rows 1, 2& 3 have soem NA values. mydata<- data.frame(matrix(seq(20*6), 20, 6)) mydata[1,3:5]<- NA mydata[2,2:3]<- NA mydata[2,5]<- NA mydata[3,6]<- NA mydata[1:3,] #this loop accomplishes the task; I am tryign toi learn a "better" way for(i in (ncol(mydata)-1):1 ){ mydata[,i]<- ifelse(is.na(mydata[,i])==TRUE,mydata[,i+1],mydata[,i]) } mydata[1:3,] #Thank you. I appreciate the help. [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.
-- Peter Ehlers University of Calgary ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.