Search code examples
rsubtraction

Subtracting Values in Previous Rows: Ecological Lifetable Construction


I was hoping I could get some help. I am constructing a life table, not for insurance, but for ecology (a cross-sectional of the population of a any kind of wild fauna), so essentially censoring variables like smoker/non-smoker, pregnant, gender, health-status, etc.:

AgeClass=C(1,2,3,4,5,6)
SampleSize=c(100,99,87,46,32,19)
for(i in 1:6){
+ PropSurv=c(Sample/100)
+ }
> LifeTab1=data.frame(cbind(AgeClass,Sample,PropSurv))

Which gave me this:

ID  AgeClas  Sample  PropSurv
1    1       100       1.00
2    2        99       0.99
3    3        87       0.87
4    4        46       0.46
5    5        32       0.32
6    6        19       0.19

I'm now trying to calculate those that died in each row (DeathInt) by taking the initial number of those survived and subtracting it by the number below it (i.e. 100-99, then 99-87, then 87-46, so on and so forth). And try to look like this:

ID  AgeClas   Sample   PropSurv  DeathInt
 1     1       100       1.00       1
 2     2        99       0.99       12
 3     3        87       0.87       41
 4     4        46       0.46       14
 5     5        32       0.32       13
 6     6        19       0.19       NA

I found this and this, and I wasn't sure if they answered my question as these guys subtracted values based on groups. I just wanted to subtract values by row.

Also, just as a side note: I did a for() to get the proportion that survived in each age group. I was wondering if there was another way to do it or if that's the proper, easiest way to do it.

Second note: If any R-users out there know of an easier way to do a life-table for ecology, do let me know!

Thanks!


Solution

  • If you have a vector x, that contains numbers, you can calculate the difference by using the diff function.

    In your case it would be

    LifeTab1$DeathInt <- c(-diff(Sample), NA)