Reputation: 705
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
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 asNA
.
Upvotes: 9