compute a difference between succesive values of a variable

Hello,

I would like to compute the difference between the treecover in year n and year n-1 of each protected area (for ex, treecover of Mont Peko National Park in 2001 - treecover of Mont Peko National Park in 2000). Please see below the screenshot.

I tried this :
treeloss <- treeloss %>%
group_by(nm_ap) %>%
mutate(treecov_var = diff(treecover))%>%
ungroup()

But I get an error message : Error in mutate():
! Problem while computing treecov_var = diff(treecover).
:heavy_multiplication_x: treecov_var must be size 21 or 1, not 20.
:information_source: The error occurred in group 1: nm_ap = "Aiguille de Prony".
Run rlang::last_error() to see where the error occurred.

What is the issue ?
thank you
regards

I suggest you use the lag() function to make a new column and then subtract.

tree_loss <- data.frame(nm_ap = rep(c("A","B"), each = 4),
                        year = rep(2013:2016, 2),
                        treecover = rnorm(8, mean = 1000, sd = 50))
tree_loss
#>   nm_ap year treecover
#> 1     A 2013 1031.2514
#> 2     A 2014 1087.2135
#> 3     A 2015  939.8167
#> 4     A 2016  965.0398
#> 5     B 2013 1034.1037
#> 6     B 2014 1002.6314
#> 7     B 2015 1067.1346
#> 8     B 2016 1018.6524
library(dplyr)

tree_loss <- tree_loss |> group_by(nm_ap) |> 
  mutate(LAG = lag(treecover),
         Loss = treecover - LAG)
tree_loss
#> # A tibble: 8 × 5
#> # Groups:   nm_ap [2]
#>   nm_ap  year treecover   LAG   Loss
#>   <chr> <int>     <dbl> <dbl>  <dbl>
#> 1 A      2013     1031.   NA    NA  
#> 2 A      2014     1087. 1031.   56.0
#> 3 A      2015      940. 1087. -147. 
#> 4 A      2016      965.  940.   25.2
#> 5 B      2013     1034.   NA    NA  
#> 6 B      2014     1003. 1034.  -31.5
#> 7 B      2015     1067. 1003.   64.5
#> 8 B      2016     1019. 1067.  -48.5

Created on 2023-05-08 with reprex v2.0.2

This topic was automatically closed 21 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.