In the Iris dataset Species is a factor variable with 3 levels("setosa" "versicolor" "virginica"). I would like to create 3 additional columns named ("setosa" "versicolor" "virginica") with False and True as logical factor variable for each column. In short: I would like to dichotomize the levels of the variable Species in the Iris dataset into 3 new columns as a logical variable. My code works, but I wonder if there is a more straight way:
df <- iris %>%
select(Species) %>%
mutate(setosa = case_when(Species=="setosa" ~ 1,
TRUE ~ 0),
versicolor = case_when(Species=="versicolor" ~ 1,
TRUE ~ 0),
virginica = case_when(Species=="virginica" ~ 1,
TRUE ~ 0),
)
df$setosa <- as.logical(df$setosa)
df$versicolor <- as.logical(df$versicolor)
df$virginica <- as.logical(df$virginica)