r - 将数据从 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 =<)
解决方案
我们可以arrange
将数据基于household_id
andage
和for每个得到替换为0后household_id
的累积值之和。potential_child
NA
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))
推荐阅读
- spring - Logback 配置问题
- python - 是否可以限制while循环的内存使用?
- python - 如何打印文件的所有行,除了在python中用(“#”)注释
- python - Django - 如何将下拉选择列表过滤为 ForeignKey
- javascript - 未处理的承诺拒绝条带支付意图示例
- c++ - 为什么模板化的基类不允许访问子类中的受保护成员,而这些子类可以在没有模板的情况下访问?
- javascript - 本地主机在 Docker 中无法用于生产
- javascript - 如何将新属性添加到数组的每个对象中
- sql - oracle中列的层次总和
- c++11 - 时间:2019-05-10 标签:c++mqtt testing automatic_reconnect