如何使用mutate和ifelse将数值变量转换为具有多个级别的因子变量

Mic*_*ael -1 r

我很难从预先存在的数值变量创建一个新的因子变量.我有一个数字变量Age和我参与者的年龄,但是想要创建一个因子变量,将参与者的年龄分类到不同的类别.每当我运行我的代码时,我都会收到错误:

"错误:缺少参数"no",没有默认值."

我尝试过以下代码的不同变体,例如没有引号的新因子级别,使用:for range等.我的代码如下.

data.frame%>%
    mutate(Age = ifelse(Age < 20, "0"),
           ifelse(Age >= 20 & Age <= 29, "1"),
                  ifelse(Age >=30 & Age <= 39, "2"),
                        ifelse(Age >= 40 & Age <=49, "3"),
                               ifelse(Age >= 50 & Age <= 59, "4"),
                                     ifelse(Age >= 60 & Age <= 69, "5"),
                                           ifelse(Age >= 70, "6", NA))
Run Code Online (Sandbox Code Playgroud)

Ben*_*ker 5

cut() 是最简单的方法.

在基地R:

Age <- seq(10,80,by=10)
cut(Age,breaks=c(-Inf,seq(20,70,by=10),Inf),
        right=FALSE,
        labels=as.character(0:6))
Run Code Online (Sandbox Code Playgroud)

我会让你随心所欲地嵌入它mutate().

您的代码存在的问题是您没有正确嵌套的选择:请仔细比较此代码段与您的代码...

Age = ifelse(Age < 20, "0",
         ifelse(Age >= 20 & Age <= 29, "1",
            ifelse(...,[yes],[no])))
Run Code Online (Sandbox Code Playgroud)