Stewart Wiseman
Stewart Wiseman

Reputation: 705

Factor with 4 levels False, FALSE, True, TRUE but need just 2 levels

I have a column in a dataframe set as factor with 4 levels

False, FALSE, True, TRUE

I need to reduce to 2 levels

FALSE, TRUE

I have done this (which works fine) but is there a better way:

df$col1 <- as.character(df$col1)    # change the factor to chr
df$col1 <- toupper (df$col1)        # Ensure all are uppercase
df$col1 <- as.factor(df$col1)       # change back

Upvotes: 2

Views: 194

Answers (1)

sgibb
sgibb

Reputation: 25736

Simply use as.logical:

d <- c("False", "FALSE", "True", "TRUE")
factor(as.logical(d))
# [1] FALSE FALSE TRUE  TRUE 
# Levels: FALSE TRUE

From ?as.logical:

Character strings c("T", "TRUE", "True", "true") are regarded as true, c("F", "FALSE", "False", "false") as false, and all others as NA.

Upvotes: 9

Related Questions