0

I am having problems converting a list to a factor in R, for data analysis. I want to bundle my age variable and am getting a list. When I try to convert it to a factor I get the following error :

Error in sort.list(y) : 'x' must be atomic for 'sort.list' Have you called 'sort' on a list?

This is my code:

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)

Any solution?

smci
  • 32,567
  • 20
  • 113
  • 146
Fred11
  • 31
  • 1
  • 5

1 Answers1

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"
Onyambu
  • 67,392
  • 3
  • 24
  • 53