0
votes

I need to apply an user function to a part of a data.frame. In a previous question I learned to use lapply for this. I have now a function that needs 2 parameters:

truncar<-function(tbl, x){if(class(tbl[[x]])=='factor') {
  tbl[,x]=as.character(tbl[[x]])
  tbl[tbl[,x]=='**',x]<-0                  
  tbl[,x]=as.numeric(tbl[[x]])}
  tbl[is.na(tbl[,x]),x]<-0
  y=ifelse(tbl[,x]>0,1,0)
  return(y)}

This code works. An example table might be:

df <- data.frame(A=c(-3:6, '**'), B=-1:9, C=c(-2:7,NA), D=factor(-3:7))

And if I apply it to one column each time, I get the desired result:

> truncar(df, 'A')
 [1] 0 0 0 0 1 1 1 1 1 1 0

But if I try to do this for many variables with lapply I get an error message:

factors<-c('A', 'B', 'C')
lapply(df[,factors], truncar)

Error in NextMethod("[[") : argument "x" is missing, with no default

I understand that this might be due to the fact that my function needs 2 parameters. How can I obtain the result for all the variables that are in the list?

1

1 Answers

1
votes

I think that what you want is

lapply(factors, function(x) truncar(df, x))

This calls the truncar function on df for each factor in factors.