Reputation: 49
My variable (poor
) is a factor with 2 levels: Poor and Non-Poor.
I need it to be 1 if it's Poor and 0 if it's Non-Poor, so i converted it to numeric (with as.numeric
, and then changed it to factor again, with as.factor
, but the levels now are 1 and 2 instead of 1 and 0.
How do i change it?
Upvotes: 4
Views: 13681
Reputation: 388817
You can index data based on it's factor level. Using @Georgery's data
poor <- factor(c("Poor", "Non-poor", "Poor", "Non-poor"))
c(0, 1)[poor]
#[1] 1 0 1 0
Or use labels
factor(c("Poor", "Non-poor", "Poor", "Non-poor"), labels = c(0, 1))
#[1] 1 0 1 0
#Levels: 0 1
Upvotes: 4
Reputation: 8117
You want to check where poor
is "Poor"
and where not. So,
poor <- factor(c("Poor", "Non-poor", "Poor", "Non-poor"))
poor == "Poor"
This gives you TRUE
/ FALSE
for that question. If you turn that into a numeric vector, like so
as.numeric(poor == "Poor")
TRUE
s are converted to 1s and FALSE
s are converted to 0.
Upvotes: 4