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?
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")
TRUEs are converted to 1s and FALSEs are converted to 0.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With