I\'m trying to calculate the minimum values of a numeric column for each level of a factor, while keeping values of another factor in the resulting data frame.
Just to show that there's always multiple ways to skin a cat:
Using ave
to get the indexes of the minimum rows in each group:
dat[which(ave(dat$value,dat$code,FUN=function(x) x==min(x))==1),]
# code index value
#1 HH11 023434 24.1
#2 HH45 3377477 37.2
#5 JL03 1177777 20.0
This method also has the potential benefit of returning multiple rows per code
group in the instance of multiple values being the minimum.
And another method using by
:
do.call(rbind,
by(dat, dat$code, function(x) cbind(x[1,c("code","index")],value=min(x$value)))
)
# code index value
# HH11 HH11 023434 24.1
# HH45 HH45 3377477 37.2
# JL03 JL03 3388595 20.0