将列表转换为R中的因子

时间:2018-02-11 10:02:04

标签: r

我在将列表转换为R中的因子时遇到问题,无法进行数据分析。我想捆绑我的年龄变量并获得一个列表。当我尝试将其转换为因子时,我收到以下错误:

  

sort.list(y)中的错误:'x'必须是'sort.list'的原子'你有没有在列表上调用'sort'?

这是我的代码:

group_age <- function(age) {
  if (age>=0&age<=20) {
    return("Age of 0-20")
  } else if(age>20&age<=30) {
    return("Age of 21-30")
  } else if (age>30&age<=40) {
    return("Age of 31-40")
  } else if (age>40&age<=50) {
    return("Age of 41-50")
  } else if (age>60) {
    return("More than 60")
  }
}

edu$age_group <- sapply(edu$age,group_age)
edu$age_group <- as.factor(edu$age_group)

任何解决方案?

1 个答案:

答案 0 :(得分:1)

 group_age=function(age){
    x=c("Age of 0-20","Age of 21-30","Age of 31-40","Age of 41-50","Age of 51-60","More than 60")
    y=c(0,20,30,40,50,60,130)
    cut(age,breaks = y,labels = x)
  }

 group_age(c(23,43,11,76,34,55))
[1] Age of 21-30 Age of 41-50 Age of 0-20  More than 60 Age of 31-40 Age of 51-60
Levels: Age of 0-20 Age of 21-30 Age of 31-40 Age of 41-50 Age of 51-60 More than 60

as.character(group_age(10))
[1] "Age of 0-20"