简体   繁体   中英

Finding a maximum value dependent on another variable

I observed some samples over a longer period of time and measured one variable(say "rel.Volume"). That gives me a data frame of the following structure:

Label   Sap_Heart Test_Group Duration rel.Volume
   <chr>   <chr>     <chr>         <dbl>      <dbl>
 1 L_TS_13 sap       RH75_33        NA        0.865
 2 L_TS_13 sap       RH75_33         0        1    
 3 L_TS_13 sap       RH75_33        16.0      1.01 
 4 L_TS_13 sap       RH75_33        24.5      1.01 
 5 L_TS_13 sap       RH75_33        40.0      1.01 
 6 L_TS_13 sap       RH75_33        64.0      1.01 
 7 L_TS_13 sap       RH75_33        88.0      1.02 
 8 L_TS_13 sap       RH75_33       184.       1.02 
 9 L_TS_13 sap       RH75_33       208.       1.02 
10 L_TS_13 sap       RH75_33       216.       1.01 
11 L_TS_13 sap       RH75_33       232.       1.02 
12 L_TS_13 sap       RH75_33       240.       1.04 
13 L_TS_13 sap       RH75_33       256.       1.02 
14 L_TS_13 sap       RH75_33       336.       0.990
15 L_TS_13 sap       RH75_33       352.       0.984
16 L_TS_13 sap       RH75_33       360.       0.950
...
...

Now, what I want is for each sample the maximum rel.Volume but also the Duration at which the maximum Volume was measured. Something like this:

Label   max.Volume max.Duration 
   <chr>   <dbl>     <dbl>     
 1 L_TS_1  1.432     290        
 2 L_TS_2  1.234     270       
 3 L_TS_3  1.323     240 
...
... 
 13 L_TS_13  1.04     240   

My problem is that I don't find the according Duration. There has to be simple solution, right?

I tried it like this:

df%>%
group_by(Label)%>%
  summarise(max.swelling = max(rel.Volume), 
            max.Durarion = Duration[rel.Volume = max(rel.Volume)])

Can't test without reproducible example but what happens when you do?

df %>%
  group_by(Label,rel.Volume)%>% 
  summarise(max.Duration = max(Duration,na.rm=TRUE)) %>%
  filter(rel.Volume = max(Volume)) %>%
  rename(max.Volume = rel.Volume)

Assuming your data is in a data frame called d , here is a tidyverse solution that I think gives you what you want.

d %>% 
   group_by(Label) %>% 
   slice_max(rel.Volume)
# A tibble: 1 x 5
# Groups:   Label [1]
  Label   Sap_Heart Test_Group Duration rel.Volume
  <fct>   <fct>     <fct>         <dbl>      <dbl>
1 L_TS_13 sap       RH75_33         240       1.04

Like Deter11, I feel a reprex showing desired output would be helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM