简体   繁体   中英

How do I make a cohort life expectancy data table in R?

Say if I have a data frame like this:

df <- data.frame(Year = c(2019,2019,2019,2020,2020,2020,2021,2021,2021), Age = c(0,1,2,0,1,2,0,1,2), px = c(0.99,0.88,0.77,0.99,0.88,0.77,0.99,0.88,0.77))

Which should look like this

> df
  Year Age   px
1 2019   0 0.99
2 2019   1 0.88
3 2019   2 0.77
4 2020   0 0.99
5 2020   1 0.88
6 2020   2 0.77
7 2021   0 0.99
8 2021   1 0.88
9 2021   2 0.77

How do I make a cohort life expectancy table so that it looks like this:

  Year Age   px
1 2019   0 0.99
2 2020   1 0.88
3 2021   2 0.77

I suggest using package dplyr

df %>%
  filter(as.numeric(as.character(Year)) - as.numeric(as.character(Age)) == 2019)
#  A tibble: 3 x 4
#      id  Year   Age    px
#   <dbl> <dbl> <dbl> <dbl>
# 1     1  2019     0  0.99
# 2     5  2020     1  0.88
# 3     9  2021     2  0.77

Included @Ian Campbell's improvement.

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