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)
Run Code Online (Sandbox Code Playgroud)
使用其中任何一个:
iris %>% cbind(sapply(levels(.$Species), `==`, .$Species))
iris %>% cbind(model.matrix(~ Species + 0, .) == 1)
iris %>% cbind(outer(.$Species, setNames(levels(.$Species), levels(.$Species)), "=="))
expand_factor <- function(f) {
m <- matrix(0, length(f), nlevels(f), dimnames = list(NULL, levels(f)))
replace(m, cbind(seq_along(f), f), 1)
}
iris %>% cbind(expand_factor(.$Species) == 1)
library(nnet)
iris %>% cbind(class.ind(.$Species) == 1)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1698 次 |
| 最近记录: |