0

I have a problem with my code. It works but returns a warning message: the condition has length > 1 and only the first element will be used. (R STUDIO)

can you help me? thank you very much

rate<- c(0.10,0.20,0.30,0.40, 0.50)
level <- c(0,10000,20000, 50000, 75000)
add <- c(0,3450, 6960, 17220, 25420)
income <-c(100, 15000, 25000, 55000, 80000)


tax <- function(x) {
  
  control <- function(i) {
    
    if(i < 5){
      
      if (x > level[i] && x <= level[i + 1]) 
        res <- rate[i] * (x - level[i]) + add[i]
      
    } else{
      
        if (x > level[i]) 
          res <- rate[i] * (x - level[i]) + add[i]
      }
    
    
  }
  
  unlist(sapply(1:5, function(i) control (i)))
  
  
}
       
sapply(1:5, FUN= function (i) paste("TAX: ", tax(income)[i]))
GuedesBF
  • 8,409
  • 5
  • 19
  • 37
Paky
  • 3
  • 1
  • The length of `x` is greater than 1, so `if (x > level[i]...)` will return a vector longer than 1. You need to vectorize across `x` as well, not just `i`. – r2evans May 29 '21 at 15:47
  • Likely a dupe of https://stackoverflow.com/q/14170778/3358272 or https://stackoverflow.com/q/10374932/3358272. – r2evans May 29 '21 at 15:49

0 Answers0