natalia
natalia

Reputation: 49

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

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

Answers (2)

Ronak Shah
Ronak Shah

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

Georgery
Georgery

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")

TRUEs are converted to 1s and FALSEs are converted to 0.

Upvotes: 4

Related Questions