Princesden
Princesden

Reputation: 169

Change multi categorical factor in R to binary

I have an R factor in with 11 categories

> predictor <- factor(V14)
> summary(predictor)
   0    1    2    3    4    5    6    7    8    9   10 
1017   20   20   20   20   20   20   20   20   20   20 

I want to turn everything that is not 0 to 1. So it should look like this

> summary(predictor)
   0    1     
1017   200 

Upvotes: 0

Views: 66

Answers (1)

Pierre L
Pierre L

Reputation: 28441

Try converting to numeric:

predictor <- factor(+(!!V14))
summary(predictor)
#   0    1 
#1017  200

Explanation

The long way is factor(as.numeric(as.logical(V14)). When numbers are coerced to logical, any number that is not zero, coerces to TRUE and 0's will be FALSE. Then turning it back to numbers from logical, any TRUE will become 1, and FALSE will be coerced to 0.

Data

V14 <- c(rep(0, 1017), rep(1:10, each=20))

Upvotes: 2

Related Questions