1

I would like to find the minimum SkinTemp value and the corresponding Time when it occurs for each id.

df<-data.frame(Time=seq(65),
               SkinTemp=rnorm(65,37,0.5),
               id=rep(1:10,c(5,4,10,6,7,8,9,8,4,4)))

I have successfully found the minimum value for each group but can't quite work out how to find the corresponding Time:

a<-aggregate(data=df,SkinTemp~id, min)

or

df %>% group_by(id) %>% summarise(minSkinTemp = min(SkinTemp))

I'm missing something like which.min, but I haven't found any examples of this being used with aggregate. Any thoughts?

HCAI
  • 2,213
  • 8
  • 33
  • 65
  • ...[this](https://stackoverflow.com/questions/43122342/how-do-i-only-keep-the-rows-with-the-lowest-and-highest-value-in-a-certain-colum), [this](https://stackoverflow.com/questions/33415297/select-minimum-data-of-grouped-data-keeping-all-columns), or [this](https://stackoverflow.com/questions/38340992/quickly-subset-dataframe-for-minumum-value-of-a-factor-level) – Henrik Mar 08 '18 at 12:28

1 Answers1

2

We can slice with which.min to get the row that have the minimum value of 'SkinTemp' after grouping by 'id'

library(dplyr)
df %>%
    group_by(id) %>%
    slice(which.min(SkinTemp))
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Thank you very much! slice is a new one for me! Just a quick question: since it gives me a tibble, should I be converting it back to a data.frame every time after I use dplyr? e.g. if I'm going to be using ggplot etc. – HCAI Mar 08 '18 at 12:18
  • 1
    @HCAI `ggplot` belongs to `tidyverse` packages along with `tibble`. So, it should work. In case, it doesn't, then after `slice` , use `%>% as.data.frame` – akrun Mar 08 '18 at 12:20