Calculate returns

Hi,

Try to create a reprex next time where we can easily access you data you copy pasted (not working now). A reprex consists of the minimal code and data needed to recreate the issue/question you're having. You can find instructions how to build and share one here:

Here is an example on how you could shift the column using the lead function from the dplyr package (Tidyverse)

library(tidyverse)

#Dummy data
myData = data.frame(
  id = rep(1:3, each = 5),
  year = rep(2010:2014, 3),
  value = runif(15)
)

#Use lead() to shift all values up per id
myData %>% arrange(id, year) %>% 
  group_by(id) %>% 
  mutate(new = lead(value)) %>% 
  ungroup()
#> # A tibble: 15 x 4
#>       id  year  value     new
#>    <int> <int>  <dbl>   <dbl>
#>  1     1  2010 0.784   0.549 
#>  2     1  2011 0.549   0.0142
#>  3     1  2012 0.0142  0.928 
#>  4     1  2013 0.928   0.0629
#>  5     1  2014 0.0629 NA     
#>  6     2  2010 0.701   0.710 
#>  7     2  2011 0.710   0.115 
#>  8     2  2012 0.115   0.311 
#>  9     2  2013 0.311   0.726 
#> 10     2  2014 0.726  NA     
#> 11     3  2010 0.909   0.425 
#> 12     3  2011 0.425   0.706 
#> 13     3  2012 0.706   0.483 
#> 14     3  2013 0.483   0.526 
#> 15     3  2014 0.526  NA

Created on 2022-03-04 by the reprex package (v2.0.1)

Note that all values are shifted one up (assuming the years are consecutive and none are skipped). The last year for each id does not have a new value as it is the last

Hope this helps,
PJ