Search code examples
rapply

'non-numeric argument to binary operator' when running apply() on dataframe


I have a data frame like below:

x <- c(1,2,3,4)
coef_ind <- c(0.5,0.6,1,2)
type <- c("power","power","expo","expo")
tf <- data.frame(x=x,coef_ind=coef_ind,type=type)

> tf
  x coef_ind  type
1 1      0.5 power
2 2      0.6 power
3 3      1.0  expo
4 4      2.0  expo

and I have wrote a function like below:

cal <- function(df){
  
  x = df['x']
  type = df['type']
  coef = df['coef_ind']
  
  if(type == "power"){
    outcome = x^coef
  }
  
  if(type == "expo"){
    outcome = 1- exp(- coef*x)
  }
  return(outcome)
}

Now, I want to apply the function to each table row. Thus:

apply(tf,1,cal)

However, I get the error hint

Error in x^coef : non-numeric argument to binary operator
enter code here

Could you please share your knowledge concerning this issue? Thank you very much.


Solution

  • Since apply casts to matrix, every value needs to be of the same type. If there's a string or character column present, everything gets cast to strings. You can still use your function by forcing the numerical values back to numeric.

    cal <- function(df){
      
      x = as.numeric(df['x'])
      type = df['type']
      coef = as.numeric(df['coef_ind'])
      
      if(type == "power"){
        outcome = x^coef
      }
      
      if(type == "expo"){
        outcome = 1- exp(- coef*x)
      }
      return(outcome)
    }
    
    apply(tf, 1, cal)
    [1] 1.0000000 1.5157166 0.9502129 0.9996645