[R] Minimum value by ID

Dimitris Rizopoulos d.rizopoulos at erasmusmc.nl
Tue May 17 15:50:40 CEST 2011


have a look at help file of function tapply(), and try this:

with(dat, tapply(x, id.var, min))


I hope it helps.

Best,
Dimitris


On 5/17/2011 3:44 PM, Downey, Patrick wrote:
> Hello,
>
> I have a longitudinal dataset where each individual has a different number
> of entries. Thus, it is of the following structure:
>
> x<- runif(12)
> id.var<- factor(c(rep("D1",4),rep("D2",2),rep("D3",3),rep("D4",3)))
> dat<- as.data.frame(x)
> dat$id.var<- id.var
> dat
>
>> dat
>             x         id.var
> 1  0.9611269     D1
> 2  0.6738606     D1
> 3  0.9724301     D1
> 4  0.9787778     D1
> 5  0.2468355     D2
> 6  0.7031734     D2
> 7  0.2458727     D3
> 8  0.8439799     D3
> 9  0.5223196     D3
> 10 0.6930475     D4
> 11 0.8887677     D4
> 12 0.5483756     D4
>
> I want to create a vector with length equal to the number of unique id.var
> and which has the minimum value for each id.var. That is, I want a vector
> which holds the minimum value for each person in my dataset.
>
> The following works, but I'm sure there is something more efficient. I
> would assume there is a function for this, but couldn't find anything.
>
> id<- levels(id.var)
> min<- rep(0,length(id))
> for(i in 1:length(id)){
>    min[i]<- min(dat$x[dat$id.var==id[i]])
> }
> min
>
>> min
> [1] 0.6738606 0.2468355 0.2458727 0.5483756
>
> Thank you in advance,
> Mitch
>
> ______________________________________________
> 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.
>

-- 
Dimitris Rizopoulos
Assistant Professor
Department of Biostatistics
Erasmus University Medical Center

Address: PO Box 2040, 3000 CA Rotterdam, the Netherlands
Tel: +31/(0)10/7043478
Fax: +31/(0)10/7043014
Web: http://www.erasmusmc.nl/biostatistiek/



More information about the R-help mailing list