#Package
library(tidyverse)
Example Data ------------------------------------------------------------
df<-tribble(
~id, ~sex, ~educ, ~income, ~job,
1, "H1", 7 , 35, "Delhi",
2, "H2", 12, 67, "Delhi",
3, "W1", 9, 42, "Kochi",
4 , "H3",15, 78, "Mumbai",
5, "W3", 6, 25, "Kolkata",
6, "W2", 13, 70, "Jaipur"
)
#Problem
df %>%
mutate(
pe= case_when(
sex=="H1"~educ[sex=="W1"],
sex=="H2"~educ[sex=="W2"],
sex=="H3"~educ[sex=="W3"]
)
)
#> # A tibble: 6 x 6
#> id sex educ income job pe
#>
#> 1 1 H1 7 35 Delhi 9
#> 2 2 H2 12 67 Delhi 13
#> 3 3 W1 9 42 Kochi NA
#> 4 4 H3 15 78 Mumbai 6
#> 5 5 W3 6 25 Kolkata NA
#> 6 6 W2 13 70 Jaipur NA
The problem is I want the output in "pe" column for "W1", "W2", "W3" also where "pe" for "W1" is educ of "H1", "pe" for "W2" is educ of "H2" etc. I do not want to copy paste the code within case_when. is there any way to do this in a better way?