Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extra column based on paired data (mutate)

Tags:

merge

r

dplyr

I have a dataset with paired data (members of same household).

Id is the individual identifier and householdid is the identifier of the partner (and vice versa).

What I need is to add an extra column (the occupation) for each id of his\her partner.

My data look like this

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"

What I need should look like this

 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"

I guess there is a solution with mutate, but I am not sure what the group_by should be.

Any ideas ?

like image 699
giac Avatar asked Jun 06 '15 12:06

giac


1 Answers

Try

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

If the data is already ordered,

 indx <- c(rbind(seq(2, nrow(dta), by=2), seq(1, nrow(dta), by=2)))
 cbind(dta, occupPartner=dta[,3][indx])
like image 66
akrun Avatar answered Sep 26 '22 03:09

akrun