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.
With the dplyr
and data.table
packages, you can do the following. You can get an index for the row having the minimum value for each group. You can use that in slice()
if you use dplyr
. You can achieve the same subsetting using .SD
if you use data.table
.
library(dplyr)
library(data.table)
dat %>%
group_by(code) %>%
slice(which.min(value))
# code index value
#
#1 HH11 023434 24.1
#2 HH45 3377477 37.2
#3 JL03 1177777 20.0
setDT(dat)[, .SD[which.min(value)], by = code]
# code index value
#1: HH11 023434 24.1
#2: HH45 3377477 37.2
#3: JL03 1177777 20.0