gpt4 book ai didi

r - 如何折叠 R 中分类变量的水平

转载 作者:行者123 更新时间:2023-12-05 08:44:54 25 4
gpt4 key购买 nike

我有各种分类变量,每个分类变量都超过 5 个级别,我想要一个可以将它们折叠成两个级别的函数

column1<- c("bad","good","nice","fair","great","bad","bad","good","nice",
"fair","great","bad")
column2<- c("john","ben","cook","seth","brian","deph","omar","mary",
"frank","boss","kate","sall")

df<- data.frame(column1,column2)

所以对于上面的数据框,在 column1 中,我想用一个函数将所有“bad”转换为“bad”,将其他级别转换为“others”。我不知道该怎么做。谢谢

最佳答案

使用ifelsecase_when

library(dplyr)
df <- df %>%
mutate(column1 = case_when(column1 != "bad" ~ "others", TRUE ~ column1))

此外,由于只有一个变化,我们可以这样做

df$column1[df$column1 != "bad"] <- "others"

关于r - 如何折叠 R 中分类变量的水平,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74788905/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com