R-创建一个变量来记录组中其他成员的分类信息

问题描述

我有一个家庭数据集data,每个家庭都由变量id标识,每个人都由id + num标识(家庭编号+家庭成员)。对于每个人,我都有各种人口统计特征,例如:

id  num  age  wage     edu            marital_status
1   1    33   1200    Secondary       Married/Cohabitating
1   2    35   1100    College         Married/Cohabitating
1   3    12   -1      Not applicable  Not applicable
2   1    27   1600    College         Single
3   1    59   2000    Secondary       Married/Cohabitating
3   2    51   1800    Other           Married/Cohabitating

       

我创建了一组变量,用于记录家庭另一成员的特征。 因此,例如,我想为有两个已婚或同居成人的家庭提供一个“伴侣工资” wage_p的变量,该变量是通过

获得的
sums = tapply(data$wage,data$id,sum)
data$wage_tot = sums[match(data$id,names(sums))]
data$wage_tot[!(data$id %in% data$id[duplicated(data$id)])] = NA
data$wage_p = data$wage_tot - data$wage

基本上,我将每个家庭的wage相加得出wage_tot,然后减去wage得到wage_p.

之所以工作,是因为我首先将数据集限制为已婚或同居的个人(所以我每个家庭只有1或2个人)。 (我知道这可能比必要的要复杂得多。)

我的结果:

id  num  age  wage     edu            marital_status        wage_tot   wage_p
1   1    33   1200    Secondary       Married/Cohabitating   2300      1100
1   2    35   1100    College         Married/Cohabitating   2300      1200
2   1    27   1600    College         Single                 NA         NA
3   1    59   2000    Secondary       Married/Cohabitating   3800      1800
3   2    51   1800    Other           Married/Cohabitating   3800      2000  

现在,当我要使用分类变量执行此操作时,问题就来了,因为我无法像求连续变量一样求和,然后求和。 例如,如果我要创建一个记录配偶受教育程度的变量edu_p

id  num  age  wage     edu            marital_status         edu_p
1   1    33   1200    Secondary       Married/Cohabitating   College
1   2    35   1100    College         Married/Cohabitating   Secondary
2   1    27   1600    College         Single                 NA
3   1    59   2000    Secondary       Married/Cohabitating   Other
3   2    51   1800    Other           Married/Cohabitating   Secondary 

我能想到的唯一想法是将分类变量转换为数字,使用我的方法,然后再次对其进行转换,但是我敢肯定,它必须要复杂得多。

有人可以帮我吗?

解决方法

请考虑一个merge解决方案,以使用id将每对夫妇进行比较。最终的左联接merge过去曾包含原始数据的非耦合观测值。

spouse_merge <- subset(merge(data,data,by="id",suffixes=c("","_p")),(num < num_p | num > num_p) & 
                       marital_status != "Not applicable" &
                       marital_status_p != "Not applicable")

final_df <- merge(data,spouse_merge[c(1,2,grep("_p",names(spouse_merge)))],by=c("id","num"),all.x=TRUE)
final_df

Online Demo

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...