Recoding data from 1,1,1, to 1,2,3

Viewed 37

So I have this dataframe. Under the column potential_child, I want to recode the values so that the oldest child == 1, the second oldest == 2, third oldest == 3, etc. I have the ages of the children, but I am floundering how to do this exactly.

DHS1 <- structure(list(person_id = c(1, 2, 1, 2, 3, 4, 1, 7, 1, 2), household_id = c(1,1, 6, 6, 6, 6, 7, 63342, 63344, 63344), year = c(2018, 2018,2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018), month = c(1,1, 1, 1, 1, 1, 1, 12, 12, 12), sex = c(2, 1, 1, 2, 1, 2, 1, 1,1, 2), age = c(28, 28, 44, 37, 10, 10, 60, 65, 55, 55), potential_mom = c(1,NA, NA, 1, NA, NA, NA, NA, NA, 1), potential_child = c(NA, NA,NA, NA, 1, 1, NA, NA, NA, NA), momloc = c(0, 0, 0, 0, 2, 2, 0,0, 0, 0), num_child = c(0, 0, 0, 0, 1, 1, 0, 0, 0, 0)), row.names = c(NA,-10L), class = c("tbl_df", "tbl", "data.frame"))

Me trying to think it through (apologies in advance for this ugly rambling):

mutate(potential_child2 = if potential_child == 1 & age =<)
1 Answers

We can arrange the data based on household_id and age and for each household_id get the cumulative sum of potential_child value after replacing NA with 0.

library(dplyr)

DHS1 %>%
  arrange(household_id, age) %>%
  group_by(household_id) %>%
  #Or if you also want to do it for every person
  #group_by(person_id, household_id) %>%
  mutate(potential_child = cumsum(replace(potential_child, 
                                   is.na(potential_child), 0)), 
         potential_child = replace(potential_child, potential_child == 0, NA))
Related