Re: [R] Minimum value by ID

From: John Kane <jrkrideau_at_yahoo.ca>
Date: Tue, 17 May 2011 07:09:40 -0700 (PDT)


A bit convolulted but it works

library(reshape2)
yy <- melt(dat)
zz <- cast(yy, id.var ~ variable, min)
zz[,2]

> 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. Received on Tue 17 May 2011 - 14:13:03 GMT

This quarter's messages: by month, or sorted: [ by date ] [ by thread ] [ by subject ] [ by author ]

All messages

Archive maintained by Robert King, hosted by the discipline of statistics at the University of Newcastle, Australia.
Archive generated by hypermail 2.2.0, at Tue 17 May 2011 - 14:40:08 GMT.

Mailing list information is available at https://stat.ethz.ch/mailman/listinfo/r-help. Please read the posting guide before posting to the list.

list of date sections of archive