How to undo accumulated values in R by specifc IDs?

Viewed 25

I have a data set where each row contains the accumulated number of offspring of a female each year. Some individuals die from one year to the next.

 Year    ID Sex      AccumulatedFecundity
     1  2411 female   29
     1   583 female   30
     1   469 female   147
     2  2290 female   161
     2   583 female   169
     2   788 female   27

I would like to undo this accumulation and get the raw values. In my example the second appearance of female 583 should get a raw value of 139 (169-30).

1 Answers

We could do a diff grouped by 'ID' and 'Sex'

library(dplyr)
df1 %>%
   group_by(ID, Sex) %>%
   mutate(old = c(first(AccumulatedFecundity), diff(AccumulatedFecundity))) %>%
   ungroup

-output

# A tibble: 6 x 5
#   Year    ID Sex    AccumulatedFecundity   old
#  <int> <int> <chr>                 <int> <int>
#1     1  2411 female                   29    29
#2     1   583 female                   30    30
#3     1   469 female                  147   147
#4     2  2290 female                  161   161
#5     2   583 female                  169   139
#6     2   788 female                   27    27

data

df1 <- structure(list(Year = c(1L, 1L, 1L, 2L, 2L, 2L), ID = c(2411L, 
583L, 469L, 2290L, 583L, 788L), Sex = c("female", "female", "female", 
"female", "female", "female"), AccumulatedFecundity = c(29L, 
30L, 147L, 161L, 169L, 27L)), class = "data.frame", row.names = c(NA, 
-6L))
Related