Mean on interval

Hi all,

Hello,
I have a df like this where for the same station I have values ​​of environmental variables at different depths.
Here for station A1, I have values ​​and 1 to 4m,
For A2, from 1 to 6m.
What I would like is to have the average of these environmental values ​​for the strat [1-4m] for A1 and [1-6m] for A2.
Basically have a single line per station where I have the average of my environmental variables

df <- tribble(
  ~station, ~depth, ~Temp, ~Sal, ~PProd, 
  "A1",1, 2.5, -0.65, -0.23
  "A1",2, 2.8, -0.57, -0.28
  "A1",3, 2.6, -0.28, -0.25
  "A1",4, 2.6,  -0.15, -0.21
  "A2",1, 2.48, -0.58, -0.29
  "A2",2, 2.54, -0.47, -0.26
  "A2",3, 2.8, -0.35, -0.21
  "A2",4, 2.74,  -0.31, -0.18
  "A2",5, 3.05,  -0.30, -0.16
  "A2",6, 3.18,  -0.27, -0.15

Thanks !

Hi @Hersh,

I think something like this should work for your case:

library(dplyr)

df <- tribble(
  ~station, ~depth, ~Temp, ~Sal, ~PProd, 
  "A1",1, 2.5, -0.65, -0.23,
  "A1",2, 2.8, -0.57, -0.28,
  "A1",3, 2.6, -0.28, -0.25,
  "A1",4, 2.6,  -0.15, -0.21,
  "A2",1, 2.48, -0.58, -0.29,
  "A2",2, 2.54, -0.47, -0.26,
  "A2",3, 2.8, -0.35, -0.21,
  "A2",4, 2.74,  -0.31, -0.18,
  "A2",5, 3.05,  -0.30, -0.16,
  "A2",6, 3.18,  -0.27, -0.15
)

df
#> # A tibble: 10 × 5
#>    station depth  Temp   Sal PProd
#>    <chr>   <dbl> <dbl> <dbl> <dbl>
#>  1 A1          1  2.5  -0.65 -0.23
#>  2 A1          2  2.8  -0.57 -0.28
#>  3 A1          3  2.6  -0.28 -0.25
#>  4 A1          4  2.6  -0.15 -0.21
#>  5 A2          1  2.48 -0.58 -0.29
#>  6 A2          2  2.54 -0.47 -0.26
#>  7 A2          3  2.8  -0.35 -0.21
#>  8 A2          4  2.74 -0.31 -0.18
#>  9 A2          5  3.05 -0.3  -0.16
#> 10 A2          6  3.18 -0.27 -0.15

df %>% 
  group_by(station) %>% 
  summarise(
    depth_range = paste0(min(depth), '-', max(depth), 'm'),
    n = n(),
    across(Temp:PProd, mean)
  )
#> # A tibble: 2 × 6
#>   station depth_range     n  Temp    Sal  PProd
#>   <chr>   <chr>       <int> <dbl>  <dbl>  <dbl>
#> 1 A1      1-4m            4  2.62 -0.412 -0.242
#> 2 A2      1-6m            6  2.80 -0.38  -0.208

Hi @mattwarkentin !
Thank you very much, it's what I wanted

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.