Im trying to write a function to subtract the value of one column from the previous one.
This is the set-up of my dataset:
lactation wt_jan wt_feb wt_mar wt_apr wt_may wt_jun wt_jul wt_aug wt_sep wt_oct wt_nov wt_dec
1 1 600.0 612.5 625.0 637.5 643.8 650.0 656.3 662.5 668.8 675.0 681.3 687.5
2 2 693.8 700.0 706.3 712.5 715.6 718.8 721.9 725.0 728.1 731.3 734.4 737.5
3 3 740.6 743.8 746.9 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0
4 4 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0
5 5 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0
6 6 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0 750.0
I previously had it set up to be the transpose, then do the subtration using this code:
calc_growth <- function(wt, days){
growth = (wt - lag(wt , default = first(wt)))/days
return(growth)
}
But this set-up wasn't working within my bigger project and for the 'jan' month, I need it to subtract from 'dec' of the previous lactation, not just itself.
In the end I'm looking to have an output that looks just like the input data, but with another set of columns named month_growth (e.g. jan_growth).
I tried following this one, but without much luck: subtract value from previous row by group