Doug Fir
Doug Fir

Reputation: 21212

Create as factor of true/false based on a vector of 0/1

target <- c(1,0,1,0,1,1)
target %>% as.factor(levels = c("false", "true"))
Error in as.factor(., levels = c("false", "true")) : 
  unused argument (levels = c("false", "true"))

How can I turn vector target into a factor where 1 corresponds to true and 0 corresponds to false?

Upvotes: 1

Views: 642

Answers (2)

Sathish
Sathish

Reputation: 12713

target <- c(1,0,1,0,1,1)
factor(target == 1)
# [1] TRUE  FALSE TRUE  FALSE TRUE  TRUE 
# Levels: FALSE TRUE

another way:

factor( target, levels = c(0, 1), labels = c(FALSE, TRUE) )
# [1] TRUE  FALSE TRUE  FALSE TRUE  TRUE 
# Levels: FALSE TRUE

Coercing numeric to logical type:

factor(as.logical(target))
# [1] TRUE  FALSE TRUE  FALSE TRUE  TRUE 
# Levels: FALSE TRUE

Upvotes: 1

mysteRious
mysteRious

Reputation: 4294

Here's another twist on the same... just rename levels(target). Here's your data as a factor:

> target <- as.factor(c(1,0,1,0,1,1))
> levels(target)
[1] "0" "1"

Make sure you get them in the same order as the original levels(target):

> levels(target) <- c("FALSE","TRUE")
> target
[1] TRUE  FALSE TRUE  FALSE TRUE  TRUE 
Levels: FALSE TRUE

Upvotes: 1

Related Questions