简体   繁体   中英

How to subtract one variable from another when they are on different lines (based on different years) in R?

I am just wondering if it is possible for me to find the difference (in a new column within my data frame) by subtracting the fall value (19.0) in year 0 from the spring value (33.33) in year 1. I am hoping to generate a column with the difference.

Here is the data set:

   Group.1   spring   fall   year
1  2000-01-01 46.00000 19.0    0
2  2001-01-01 33.33333 19.0    1
3  2002-01-01 37.66667 19.0    2
4  2003-01-01 31.33333 13.0    3
5  2004-01-01 35.66667 13.0    4

Is there a way to do this that is not manually writing out each step?

I expect the first row of this new column to have an NA value.

I have tried a few different ways, but I cannot seem to get all of the conditions to work the way I want them to.

How about this:

library(dplyr)
dat <- tibble::tribble(
  ~"Group.1",   ~spring,   ~fall,   ~year,
"2000-01-01", 46.00000, 19.0,    0,
"2001-01-01", 33.33333, 19.0,    1,
"2002-01-01", 37.66667, 19.0,    2,
"2003-01-01", 31.33333, 13.0,    3,
"2004-01-01", 35.66667, 13.0,    4)

dat %>% 
  mutate(diff_fall = spring - lag(fall))
#> # A tibble: 5 × 5
#>   Group.1    spring  fall  year diff_fall
#>   <chr>       <dbl> <dbl> <dbl>     <dbl>
#> 1 2000-01-01   46      19     0      NA  
#> 2 2001-01-01   33.3    19     1      14.3
#> 3 2002-01-01   37.7    19     2      18.7
#> 4 2003-01-01   31.3    13     3      12.3
#> 5 2004-01-01   35.7    13     4      22.7

Created on 2022-11-29 by the reprex package (v2.0.1)

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