Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

as.factor with levels 0, 1 instead of 1, 2

Tags:

r

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?

like image 341
natalia Avatar asked Oct 24 '25 03:10

natalia


2 Answers

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.

like image 124
Georgery Avatar answered Oct 26 '25 16:10

Georgery


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
like image 24
Ronak Shah Avatar answered Oct 26 '25 17:10

Ronak Shah



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!