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"

1
  • 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) Commented Jan 8, 2017 at 9:07

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Do you mean return(x)?
Nope, I did mean return(1), to explain the concept. Not letting OP setting this problem up as a function :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.