[R] merge two dataset and replace missing by 0

Gabor Grothendieck ggrothendieck at gmail.com
Mon Nov 15 17:13:51 CET 2010


On Mon, Nov 15, 2010 at 10:42 AM, Kate Hsu <yhsu.rhelp at gmail.com> wrote:
> Hi r users,
>
> I have two data sets (X1, X2). For example,
> time1<-c( 0,   8,  15,  22,  43,  64,  85, 106, 127, 148, 169, 190 ,211 )
> outpue1<-c(171 ,164 ,150 ,141 ,109 , 73 , 47  ,26  ,15  ,12   ,6   ,2   ,1 )
> X1<-cbind(time1,outpue1)
>
> time2<-c( 0   ,8  ,15 , 22  ,43 , 64  ,85 ,106 ,148)
> output2<-c( 5   ,5   ,4   ,5   ,5   ,4   ,1   ,2 ,  1 )
> X2<-cbind(time2,output2)
>
> I want to merge X1 and X2 into a big dataset X by time1 and time2 so that
> the missing item in output2 will be replace by 0. For example, there is no
> output2 when time2=127, then the corresponding output will be 0. Anyone know
> how to use merge command to deal with this?
>

Since these are time series you might want to use a time series
package to do this:

library(zoo)
time1<-c( 0,   8,  15,  22,  43,  64,  85, 106, 127, 148, 169, 190 ,211 )
output1<-c(171 ,164 ,150 ,141 ,109 , 73 , 47  ,26  ,15  ,12   ,6   ,2   ,1 )

time2<-c( 0   ,8  ,15 , 22  ,43 , 64  ,85 ,106 ,148)
output2<-c( 5   ,5   ,4   ,5   ,5   ,4   ,1   ,2 ,  1 )

z1 <- zoo(output1, time1)
z2 <- zoo(output2, time2)
merge(z1, z2, fill = 0)


-- 
Statistics & Software Consulting
GKX Group, GKX Associates Inc.
tel: 1-877-GKX-GROUP
email: ggrothendieck at gmail.com



More information about the R-help mailing list