Reputation: 93
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
Upvotes: 1
Views: 190
Reputation: 16988
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.
Upvotes: 3