gpt4 book ai didi

r - 基于配对数据的额外列(变异)

转载 作者:行者123 更新时间:2023-12-04 17:18:06 28 4
gpt4 key购买 nike

我有一个包含配对数据的数据集(同一家庭的成员)。

身份证 是个人标识符和 户号是合作伙伴的标识符(反之亦然)。

我需要的是为每个 添加一个额外的列(职业)。 id 他\她的伴侣。

我的数据看起来像这样

dta = rbind( c(1013661,101366, 'Never worked'), 
c(1013662, 101366, 'Intermediate occs'),
c(1037552, 103755, 'Managerial & professional occs'),
c(1037551, 103755, 'Intermediate occs')
)

colnames(dta) = c('idno', 'householdid', 'occup')
dta

idno householdid occup
"1013661" "101366" "Never worked"
"1013662" "101366" "Intermediate occs"
"1037552" "103755" "Managerial & professional occs"
"1037551" "103755" "Intermediate occs"

我需要的应该是这样的
 idno      householdid occup                            occupPartner                    
"1013661" "101366" "Never worked" "Intermediate occs"
"1013662" "101366" "Intermediate occs" "Never worked"
"1037552" "103755" "Managerial & professional occs" "Intermediate occs"
"1037551" "103755" "Intermediate occs" "Managerial & professional occs"

我想有一个 mutate 的解决方案,但我不确定 group_by 应该是什么。

有任何想法吗 ?

最佳答案

尝试

library(dplyr)
dta1 <- as.data.frame(dta) %>%
group_by(householdid) %>%
mutate(occupPartner= rev(occup))
as.data.frame(dta1)
# idno householdid occup
#1 1013661 101366 Never worked
#2 1013662 101366 Intermediate occs
#3 1037552 103755 Managerial & professional occs
#4 1037551 103755 Intermediate occs
# occupPartner
#1 Intermediate occs
#2 Never worked
#3 Intermediate occs
#4 Managerial & professional occs

如果数据已经排序,
 indx <- c(rbind(seq(2, nrow(dta), by=2), seq(1, nrow(dta), by=2)))
cbind(dta, occupPartner=dta[,3][indx])

关于r - 基于配对数据的额外列(变异),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30683092/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com