首页 > 解决方案 > 将数据从 1,1,1 重新编码到 1,2,3

问题描述

所以我有这个数据框。在列potential_child下,我想重新编码这些值,以便最老的孩子 == 1、第二大的孩子 == 2、第三大的孩子 == 3 等等。我有孩子们的年龄,但我正在苦苦挣扎怎么做这正是。

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"))

我试图仔细考虑(为这种丑陋的漫无目的提前道歉):

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

标签: rdataframetidyversedata-wrangling

解决方案


我们可以arrange将数据基于household_idandage和for每个得到替换为0后household_id的累积值之和。potential_childNA

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))

推荐阅读