I am trying to recode a race/ethnicity variable derived from a Hispanic
variable and a 6 other race
variables.
I've tried some of these methods. I can't quite figure out how to keep all my different levels for each factor.
The Hispanic
variable has 5 levels: 0:NA, 1:yes, 2:no, 3:unable to determine, 99:missing
.
Each race
variable has 3 levels: 0:does not apply, 1:applies, 99:missing
.
My new p1raceeth
variable will have 7 levels: 0:Unknown, 1:Black,NH, 2:Hispanic any race, 3:Other, 4:White,NH, 99:missing
.
I had tried also coding it with the code below and it works for the one race:amakn
variable but then when I move on the the next race
variable with the same code it overwrites the past recode. Any suggestions would be very helpful. Including suggestions on how to collapse the factor levels within the race
and Hispanic
variables to make this more manageable.
What prompted this was I was trying to combine asian
with nhopi
. Quite the rabbit hole.
d_a$p1raceeth <- "0"
d_a$p1raceeth[d_a$Hispanic=="0" & d_a$amakn=="0"] <- "0"
d_a$p1raceeth[d_a$Hispanic=="0" & d_a$amakn=="1"] <- "0"
d_a$p1raceeth[d_a$Hispanic=="0" & d_a$amakn=="99"] <- "0"
d_a$p1raceeth[d_a$Hispanic=="1" & d_a$amakn=="0"] <- "2"
d_a$p1raceeth[d_a$Hispanic=="1" & d_a$amakn=="1"] <- "2"
d_a$p1raceeth[d_a$Hispanic=="1" & d_a$amakn=="99"] <- "99"
d_a$p1raceeth[d_a$Hispanic=="2" & d_a$amakn=="0"] <- "99"
d_a$p1raceeth[d_a$Hispanic=="2" & d_a$amakn=="1"] <- "3"
d_a$p1raceeth[d_a$Hispanic=="2" & d_a$amakn=="99"] <- "99"
d_a$p1raceeth[d_a$Hispanic=="3" & d_a$amakn=="0"] <- "0"
d_a$p1raceeth[d_a$Hispanic=="3" & d_a$amakn=="1"] <- "3"
d_a$p1raceeth[d_a$Hispanic=="3" & d_a$amakn=="99"] <- "99"
d_a$p1raceeth[d_a$Hispanic=="99" & d_a$amakn=="0"] <- "99"
d_a$p1raceeth[d_a$Hispanic=="99" & d_a$amakn=="1"] <- "3"
d_a$p1raceeth[d_a$Hispanic=="99" & d_a$amakn=="99"] <- "99"
Here is a sample of my data:
df <- read.table(text=
"Hispanic amakn asian blkaa nhopi white utod
1 1 0 0 0 0 1 0
2 2 99 99 1 99 99 99
3 99 99 99 99 99 99 99
4 3 99 99 99 99 99 99
5 0 99 99 99 99 99 99
6 99 99 99 99 99 99 99
7 3 99 99 99 99 99 99
8 0 99 99 99 99 99 99
9 2 0 0 0 0 1 0
10 2 0 0 0 0 1 0
11 2 0 0 0 0 1 0
12 1 0 0 0 0 1 0
13 0 99 99 99 99 99 99
14 2 0 0 0 0 1 0
15 0 99 99 99 99 99 99
16 2 0 0 0 0 1 0
17 2 0 0 1 0 0 0
18 0 0 0 0 0 0 0
19 99 99 99 99 99 99 99
20 1 99 99 99 99 99 99
21 0 99 99 99 99 99 99
22 2 0 0 0 0 1 0
23 2 0 0 0 0 1 0
24 2 0 0 1 0 0 0
25 0 99 99 99 99 99 99
26 99 0 0 0 0 1 0
27 0 99 99 99 99 99 99
28 99 0 0 0 0 1 0
29 1 99 99 99 99 99 99
30 99 99 99 99 99 99 99
31 2 0 0 0 0 1 0
32 2 0 0 0 0 1 0
33 3 0 1 0 0 0 0
34 2 99 99 99 99 1 99
35 2 0 0 0 0 1 0
36 1 99 99 99 99 99 99
37 0 99 99 99 99 99 99
38 2 0 0 0 0 1 0
39 99 99 99 99 99 99 99
40 1 99 99 99 99 99 99
", header=TRUE)