我有多个分类变量,每个变量都有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”。我不知道该怎么做。谢谢
4条答案
按热度按时间csga3l581#
使用
ifelse
或case_when
另外,由于只有一个变化,我们可以只做
oxosxuxt2#
在以R为基数的情况下,一个简单的方法是使用索引:
hs1ihplo3#
62o28rlo4#
下面是带分组的
dplyr
解决方案: