decadal_mean_using_Tidyverse

Dear R users,

I want to do the decadal mean such as 1931-1940, 1941-1950....2091-2100.

The data looks like: regions (with 5 regions) and season = DJF,MAM,JJAS,ON

   year    SA    sd region season
   <dbl> <dbl> <dbl> <chr>  <chr> 
 1  1931  187.  58.9 KARA   DJF   
 2  1932  177.  58.4 KARA   DJF   
 3  1933  181.  58.1 KARA   DJF   
 4  1934  173.  56.0 KARA   DJF   
 5  1935  177.  54.8 KARA   DJF   
 6  1936  188.  58.9 KARA   DJF   
 7  1937  189.  60.1 KARA   DJF   
 8  1938  174.  53.5 KARA   DJF   
 9  1939  176.  53.7 KARA   DJF   
10  1940  180.  55.9 KARA   DJF   
# … with 3,390 more rows```

Could you provide some information on that. 

Thank You

You can create decadal groups using the %/% (integer division) operator:

library(tidyverse)

# Fake data
set.seed(3)
d = tibble(year= 1931:2020,
       SA = cumsum(rnorm(length(1931:2020), 0, 5)) + 50)

d
#> # A tibble: 90 x 2
#>     year    SA
#>    <int> <dbl>
#>  1  1931  45.2
#>  2  1932  43.7
#>  3  1933  45.0
#>  4  1934  39.3
#>  5  1935  40.2
#>  6  1936  40.4
#>  7  1937  40.8
#>  8  1938  46.4
#>  9  1939  40.3
#> 10  1940  46.6
#> # … with 80 more rows
# Create decade groups
d = d %>% 
  mutate(decade = (year - 1) %/% 10) %>% 
  group_by(decade) %>% 
  mutate(decade = paste(range(year), collapse="-"))

d %>% print(n=15)
#> # A tibble: 90 x 3
#> # Groups:   decade [9]
#>     year    SA decade   
#>    <int> <dbl> <chr>    
#>  1  1931  45.2 1931-1940
#>  2  1932  43.7 1931-1940
#>  3  1933  45.0 1931-1940
#>  4  1934  39.3 1931-1940
#>  5  1935  40.2 1931-1940
#>  6  1936  40.4 1931-1940
#>  7  1937  40.8 1931-1940
#>  8  1938  46.4 1931-1940
#>  9  1939  40.3 1931-1940
#> 10  1940  46.6 1931-1940
#> 11  1941  42.9 1941-1950
#> 12  1942  37.3 1941-1950
#> 13  1943  33.7 1941-1950
#> 14  1944  34.9 1941-1950
#> 15  1945  35.7 1941-1950
#> # … with 75 more rows
# Summarise by decade
d %>% group_by(decade) %>% summarise(meanSA=mean(SA))
#> `summarise()` ungrouping output (override with `.groups` argument)
#> # A tibble: 9 x 2
#>   decade    meanSA
#>   <chr>      <dbl>
#> 1 1931-1940   42.8
#> 2 1941-1950   34.0
#> 3 1951-1960   19.4
#> 4 1961-1970   31.6
#> 5 1971-1980   41.0
#> 6 1981-1990   24.1
#> 7 1991-2000   30.2
#> 8 2001-2010   41.8
#> 9 2011-2020   61.8

Created on 2020-10-27 by the reprex package (v0.3.0)

1 Like

Thanks :slight_smile:

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.