[R] Minimum value by ID

Downey, Patrick PDowney at urban.org
Tue May 17 15:44:20 CEST 2011


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



More information about the R-help mailing list