我有一个个人数据集,其中包含每个人的人口统计信息。它还提供了唯一的家庭ID以及其他变量:
id if_adult (>18 yrs old) marital_status
1 1 Single
1 1 Single
2 1 Married
2 1 Married
2 0 Married
每个家庭至少有一个成年单身成年人或两个成年已婚或单身成年人。一些家庭也有孩子。我正在尝试创建一个称为“未婚夫妇”的虚拟变量,该变量将正确地将一个正好有两个单身成年人的家庭分类。显然,有重复的行具有相同的家庭ID,因此我希望每个行都正确标记。目前,我拥有的代码是:
individual_data$`unmarried couple` <- ifelse((individual_data$if_adult ==
"1" & individual_data$id == individual_data$id) &
individual_data$marital_status == "Single", "1","0")
但这错误地将单身家庭(即单身母亲和带孩子的单身父亲)归为未婚夫妇。这是关键-如果我能弄清楚这一点,那将是准确的。为了纠正这个问题,我尝试创建一个新变量来指示每个家庭的成年人总数:
id if_adult (>18 yrs old) marital_status total_adults
1 1 Single 2
1 1 Single 2
2 1 Married 2
2 1 Married 2
2 0 Married 2
然后通过过滤掉单户家庭并将条件设置为至少有两个成年人来创建我想要的变量
individual_data$`unmarried couple` <- ifelse((individual_data$total_adults
== 2 & individual_data$id == individual_data$id) &
individual_data$marital_status == "Single", "1","0")
我最终希望它看起来像这样以及其余数据:
id if_adult marital_status total_adults unmarried couple
1 1 Single 2 1
1 1 Single 2 1
2 1 Married 2 0
2 1 Married 2 0
2 0 Married 2 0
预先感谢您的反馈和建议
答案 0 :(得分:1)
使用dplyr
和group_by
来简化此操作怎么样?它会检查每个ID是否有两个单身成年人。
library(dplyr)
dd %>%
group_by(id) %>%
mutate(unmarried_couple = sum(if_adult*(marital_status=="Single"))==2,
total_adults = sum(if_adult))
经过测试
dd <- read.table(text="id if_adult marital_status
1 1 Single
1 1 Single
2 1 Married
2 1 Married
2 0 Married", header=T)
答案 1 :(得分:0)
===最后编辑===
如果您想坚持使用Base R,那么以下解决方案可能对您有用:
individual_data$unmarried_couples <- ifelse(individual_data$marital_status %in% c("Single", "1", "0"),
individual_data$total_adults %/% 2,
0)
我使用表达式total_adults %/% 2
来计算一个家庭中未婚夫妇的数量,因为我认为一个家庭中可能有两个以上的单身成年人。
经过测试:
id if_adult (>18 yrs old) marital_status total_adults
1 1 Single 2
1 1 Single 2
2 1 Married 2
2 1 Married 2
2 0 Married 2
=== edits ==
由于您在变量adults_in_household
中苦苦挣扎,因此下面是一个完全可复制的代码:
individual_data <- data.frame(
id = c(1,1,2,2,2,3,3),
if_adult = c(1,1,1,1,0,0,0),
marital_status = c("Single", "Single", "Married", "Married", "Married", "Single", "Single")
)
library(dplyr)
individual_data %>%
group_by(id) %>%
mutate(adults_in_household = sum(if_adult))
此代码的输出应为:
# A tibble: 7 x 4
# Groups: id [3]
id if_adult marital_status adults_in_household
<dbl> <dbl> <fct> <dbl>
1 1 1 Single 2
2 1 1 Single 2
3 2 1 Married 2
4 2 1 Married 2
5 2 0 Married 2
6 3 0 Single 0
7 3 0 Single 0
希望这会有所帮助。