Estimate number of people alive for every single year between 1850 and 1950 in R

Viewed 31

I'm still having trouble regarding my workflow. I need to estimate the number of people alive by gender in every single year between 1850 and 1950. I have the following information:

id, birth_year, death_year and gender

id <- c(1:6)
birth_year <- c(1850:1855)
death_year <- c(1890:1895)
gender <- c("female", "male", "female", "male", "male", "male")
df <- data.frame(id, birth_year, death_year, gender)

Think about the steps to achieve my goal, I realize that a should add columns in my df for each year. In each column, I would estimate the age of a person iat the year x, then, the year of a person i + 1 at the year x + 1. Being i = 1 and x = 1850.

df$age1850 <- 1850 - df$birth_year
df$age1851 <- 1851 - df$birth_year
df$age1852 <- 1852 - df$birth_year
df$age1853 <- 1853 - df$birth_year
df$age1854 <- 1854 - df$birth_year
df$age1855 <- 1855 - df$birth_year

# The expected result would be:
  id birth_year death_year gender age1850 age1851 age1852 age1853 age1854 age1855
1  1       1850       1890 female       0       1       2       3       4       5
2  2       1851       1891   male      -1       0       1       2       3       4
3  3       1852       1892 female      -2      -1       0       1       2       3
4  4       1853       1893   male      -3      -2      -1       0       1       2
5  5       1854       1894   male      -4      -3      -2      -1       0       1
6  6       1855       1895   male      -5      -4      -3      -2      -1       0

Thanks in advance!

1 Answers

To estimate the number of people alive by gender in every single year between 1850 and 1950 you can use table and subset you df with the year.

df$gender <- as.factor(df$gender)
years <- 1850:1950
sapply(setNames(years, years), function(i) {table(df$gender[df$birth_year <= i &
   df$death_year >= i])})
#       1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863
#female    1    1    2    2    2    2    2    2    2    2    2    2    2    2
#male      0    1    1    2    3    4    4    4    4    4    4    4    4    4
#       1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877
#female    2    2    2    2    2    2    2    2    2    2    2    2    2    2
#male      4    4    4    4    4    4    4    4    4    4    4    4    4    4
#       1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891
#female    2    2    2    2    2    2    2    2    2    2    2    2    2    1
#male      4    4    4    4    4    4    4    4    4    4    4    4    4    4
#       1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905
#female    1    0    0    0    0    0    0    0    0    0    0    0    0    0
#male      3    3    2    1    0    0    0    0    0    0    0    0    0    0
#...
Related