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"
Problem 1.
Your function has no
return
argument.As a result, it reads that way:
… 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.