I have a tibble of 65524 observations where one variable is an ID for an household and the other is factor where the value of 1
is assigned if the age of the person in the household is less then 15y.o., 2
is assigned if the age is between 15 and 64, and 3
is assigned if the age of the person is 65 or older. The tibble look like this
> head(df, 15)
# A tibble: 15 x 2
hh.id age.cat
<dbl> <dbl+lbl>
1 11009 2
2 11009 2
3 11009 2
4 11009 2
5 11009 2
6 11009 1
7 11009 1
8 11009 1
9 11018 2
10 11018 1
11 11018 1
12 11018 1
13 11018 1
14 11018 2
15 11018 2
I need to create a variable to estimate the dependency ratio of each household. Something similar to this
> head(df, 15)
# A tibble: 15 x 3
hh.id age.cat dep.ratio
<dbl> <dbl+lbl><dbl>
1 11009 2 0.60
2 11009 2 0.60
3 11009 2 0.60
4 11009 2 0.60
5 11009 2 0.60
6 11009 1 0.60
7 11009 1 0.60
8 11009 1 0.60
9 11018 2 1.25
10 11018 1 1.25
11 11018 1 1.25
12 11018 1 1.25
13 11018 1 1.25
14 11018 2 1.25
15 11018 2 1.25
I thought that using dplyr::mutate
and dplyr::group_by
would work
df <- df %>%
dplyr::group_by(hh.id) %>%
dplyr::mutate(dep.ratio = (length(which(df$age.cat == 1)) + length(which(df$age.cat == 3)))/length(which(df$age.cat == 2)))
However, I do not get the estimates per each group (i.e. per each household), but I get the overall dependency ratio for the whole sample, repeated for each observation.
# A tibble: 15 x 3
# Groups: hh.id [2]
hh.id age.cat dep.ratio
<dbl> <dbl+lbl> <dbl>
1 11009 2 1.02
2 11009 2 1.02
3 11009 2 1.02
4 11009 2 1.02
5 11009 2 1.02
6 11009 1 1.02
7 11009 1 1.02
8 11009 1 1.02
9 11018 2 1.02
10 11018 1 1.02
11 11018 1 1.02
12 11018 1 1.02
13 11018 1 1.02
14 11018 2 1.02
15 11018 2 1.02
I then considered using tapply
, but I could not write a function which conditions on the values of hh.id
. Finally, I also tried aggregate
, but without any luck.
Any suggestion is welcome.
Thanks
Manolo