# Re: [R] unequal number of observations for longitudinal data

From: Gabor Grothendieck <ggrothendieck_at_gmail.com>
Date: Sat 27 Jan 2007 - 11:15:54 GMT

merge.zoo in the zoo package has an n-way merge supporting zero fill:

library(zoo)

DF <- data.frame(id = c(1, 1, 1, 2, 2, 2, 2, 2, 3, 3), x = c(10, 30, 20, 10, 20, 40, 80, 70, 20, 40))

as.data.frame(do.call(merge, c(lapply(unstack(DF, x ~ id), zoo), fill = 0)))

# last line can alternately be

f <- function(DF) zoo(DF\$x)
as.data.frame(do.call(merge, c(by(DF, DF\$id, f), fill = 0)))

On 1/27/07, gallon li <gallon.li@gmail.com> wrote:
> i have a large longitudinal data set. The number of observations for each
> subject is not the same across the sample. The largest number of a subject
> is 5 and the smallest number is 1.
>
> now i want to make each subject to have the same number of observations by
> filling zero, e.g., my original sample is
>
> id x
> 001 10
> 001 30
> 001 20
> 002 10
> 002 20
> 002 40
> 002 80
> 002 70
> 003 20
> 003 40
> 004 ......
>
> now i wish to make the data like
>
> id x
> 001 10
> 001 30
> 001 20
> 001 0
> 001 0
> 002 10
> 002 20
> 002 40
> 002 80
> 002 70
> 003 20
> 003 40
> 003 0
> 003 0
> 003 0
> 004 ......
>
> so that each id has exactly 5 observations. is there a function which can
> allow me do this quickly?
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help@stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help