[R] Can R fill in missing values?

Jia Ying Mei jiamei at Princeton.EDU
Thu Jul 24 05:18:34 CEST 2008


Hi,

I know this can be done in Stata (which is quite messy) but I wanted to 
know if it can be done in R. So lets say I have a merged data set (I 
used the merge function by date for the attached two files), where all 
the missing values are filled with NAs (which is what the all.x=TRUE does).

Is there any way to replace those NAs with the value of the latest row 
that contains a value?

For example:

 > Date<-read.table("Desktop/R/Testdate.txt", head=T, sep="\t")
 > Data<-read.table("Desktop/R/Testinput.txt", head=T, sep="\t")
 > Merged<-merge(Date, Data, all.x=TRUE)
 > Merged
     Date France Germany
1 3/10/07      2       4
2 3/11/07     NA      NA
3 3/12/07     NA      NA
4 3/13/07     NA      NA
5 3/14/07     NA      NA
6 3/15/07      1       2

Given this Merged data, is there a way to replace every NA value from 
3/11 to 3/14 with that of 3/15? But then say there are multiple 
intervals with NAs that I want to fill with the last given value?

Technically, I know I could just manually edit the data, but the real 
files I need to work with has thousands of rows, so I was wondering if 
there was a way to do this (probably a loop?). Thanks a bunch.

Jia Ying Mei
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Testdate.txt
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20080723/aa0e5d29/attachment.txt>
-------------- next part --------------
An embedded and charset-unspecified text was scrubbed...
Name: Testinput.txt
URL: <https://stat.ethz.ch/pipermail/r-help/attachments/20080723/aa0e5d29/attachment-0001.txt>


More information about the R-help mailing list