[R] Minimum value by ID

Ivan Calandra ivan.calandra at uni-hamburg.de
Tue May 17 16:21:06 CEST 2011


Two other options (which I prefer):
aggregate(x~id.var, data=dat, FUN=min)

or
library(doBy)
summaryBy(x~id.var, data=dat, FUN=min)

HTH,
Ivan

Le 5/17/2011 16:09, John Kane a écrit :
> A bit convolulted but it works
>
> library(reshape2)
> yy<- melt(dat)
> zz<- cast(yy, id.var ~ variable, min)
> zz[,2]
>
> --- On Tue, 5/17/11, Downey, Patrick<PDowney at urban.org>  wrote:
>
>> From: Downey, Patrick<PDowney at urban.org>
>> Subject: [R] Minimum value by ID
>> To: r-help at r-project.org
>> Received: Tuesday, May 17, 2011, 9:44 AM
>> 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.
>>
> ______________________________________________
> 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.
>

-- 
Ivan CALANDRA
PhD Student
University of Hamburg
Biozentrum Grindel und Zoologisches Museum
Dept. Mammalogy
Martin-Luther-King-Platz 3
D-20146 Hamburg, GERMANY
+49(0)40 42838 6231
ivan.calandra at uni-hamburg.de

**********
http://www.for771.uni-bonn.de
http://webapp5.rrz.uni-hamburg.de/mammals/eng/1525_8_1.php



More information about the R-help mailing list