0

I am trying to recode the following variable:

str(dades$Edat)
 num [1:30000] 24 26 34 37 57 37 29 23 28 35 ...

Into this:

agrupar.edat<-function(x){
  for (i in 1:length(x)){
    if (x[i]>=21 & x[i]<30) {x[i]<-'1'} else
      if (x[i]>=30 & x[i]<40) {x[i]<-'2'} else
        if (x[i]>=40 & x[i]<50) {x[i]<-'3'} else
          if (x[i]>=50 & x[i]<60) {x[i]<-'4'} else
            if (x[i]>=60 & x[i]<70) {x[i]<-'5'} else
        if (x[i]>=70 & x[i]<80) {x[i]<-'6'} 
  }

So I can put the results here:

edx<-agrupar.edat(dades$Edat)

But something is not working and edx keeps returning me "NULL"

Gotey
  • 449
  • 4
  • 15
  • 41
  • 3
    Just use `?cut` to do this i.e. `cut(dates$Edat, breaks = c(-Inf, -21, 30, 40, 50, 60, 80, Inf), labels = 1:6)` – akrun Jan 08 '17 at 09:07

1 Answers1

1

Problem 1.

Your function has no return argument.

As a result, it reads that way:

agrupar.edat<-function(x){
  # do stuff
  # good bye
  }

… so logically enough, nothing (NULL) comes out of it.

Try simply adding return(1) at the end, just before the closing bracket, and magic will happen.

Note, however, that your problem does not require a function. It requires…

Problem 2.

… using cut, as @akrun's comment instructs you to do.

Fr.
  • 2,865
  • 2
  • 24
  • 44