Antero Ferreira
Antero Ferreira

Reputation: 55

R script error - apply value to dataframe variable

I have a difficulty when working with a R script. If I run this line in the command line it works perfectly

dbnasc$ano[which(dbnasc$ano>=1605 & dbnasc$ano<1610)]=1605

But if define a function with the same code in it doesn't work

#Função recode
xclass1=function(ini,fim,per){
t=seq(ini,fim,by=per)
z=length(t)
i=1
while(i<z){
  a0=t[[i]]
  a1=t[[i+1]]
  dbnasc$ano[which(dbnasc$ano>=a0 & dbnasc$ano<a1)] = a0
  i=i+1
  } 
}

Upvotes: 3

Views: 182

Answers (3)

Antero Ferreira
Antero Ferreira

Reputation: 55

After check Jeff's solution my function recode looks like that:

  1. DATAFRAME

    dataframe

  2. xclass11 function to recode year from datanasc giving first, last and interval.


#Função recode
xclass11=function(ini,fim,per){
t=seq(ini,fim,by=per)
z=length(t)
i=1
ano=as.numeric(format(as.Date(dbnasc$datanasc), "%Y"))
while(i<z){
  a0=t[[i]]
  a1=t[[i+1]]
  ano[which(ano>=a0 & ano<a1)]=a0
  i=i+1
  } 
dbnasc=cbind(dbnasc,ano)
return(dbnasc)
}

To use the function

dbnasc=xclass11(1600,1900,25)

Thank you Jeff and Alexander.

Upvotes: 1

Alexander Vos de Wael
Alexander Vos de Wael

Reputation: 467

If I understand correctly, you are trying to recode an integer variable that represents a year. The required transformation is turning intervals of years into a single year. E.g. if you'd have the years c(1988, 1993, 1997, 1999), group them by decade into c(1980, 1990, 1990, 1990). If this indeed is what you desire, there's an easier method:

year.recoded <- year - year %% interval

An example in the console:

> x <- c(1988, 1993, 1997, 1999)
> x - x %% 10
[1] 1980 1990 1990 1990

Upvotes: 2

Jeff Allen
Jeff Allen

Reputation: 17517

(Almost) all functions should return something. Your function doesn't return anything, so no variable ever gets modified (except those variables that only exist temporarily in order to execute the function).

Try returning the variable you want to persist at the end of the function using the return() function, or you can omit return and just give the variable name:

#Função recode
xclass1=function(dbnasc, ini,fim,per){
  t=seq(ini,fim,by=per)
  z=length(t)
  i=1
  while(i<z){
    a0=t[[i]]
    a1=t[[i+1]]
    dbnasc$ano[which(dbnasc$ano>=a0 & dbnasc$ano<a1)] = a0
    i=i+1
  } 
  dbnasc
  #or `return(dbnasc)`
}

Now your function expects a variable named dbnasc as input and then returns that same variable with the modifications made during that function. You can call it using something like:

dbnasc <- xclass1(dbnasc, etc, etc)

if you want to assign the result back to the original variable.

Upvotes: 3

Related Questions