[R] the first and last observation for each subject

Gabor Grothendieck ggrothendieck at gmail.com
Fri Jan 2 11:56:10 CET 2009


Try this:

> Lines <- "ID x y time
+ 1  10 20 0
+ 1  10 30 1
+ 1 10 40 2
+ 2 12 23 0
+ 2 12 25 1
+ 2 12 28 2
+ 2 12 38 3
+ 3 5 10 0
+ 3 5 15 2"
> DF <- read.table(textConnection(Lines), header = TRUE)
> aggregate(DF[3], DF[1:2], function(x) tail(x, 1) - head(x, 1))
  ID  x  y
1  3  5  5
2  1 10 20
3  2 12 15


On Fri, Jan 2, 2009 at 4:20 AM, gallon li <gallon.li at gmail.com> wrote:
> I have the following data
>
> ID x y time
> 1  10 20 0
> 1  10 30 1
> 1 10 40 2
> 2 12 23 0
> 2 12 25 1
> 2 12 28 2
> 2 12 38 3
> 3 5 10 0
> 3 5 15 2
> .....
>
> x is time invariant, ID is the subject id number, y is changing over time.
>
> I want to find out the difference between the first and last observed y
> value for each subject and get a table like
>
> ID x y
> 1 10 20
> 2 12 15
> 3 5 5
> ......
>
> Is there any easy way to generate the data set?
>
>        [[alternative HTML version deleted]]
>
> ______________________________________________
> R-help at 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.
>




More information about the R-help mailing list