Home > Blockchain >  How to vectorise ifelse function in R?
How to vectorise ifelse function in R?

Time:05-13

I am trying to make a vectorized function using ifelse in R, but my code is only taking the first element of the vector. For example, as shown in my code below when I assigned "y" to the Years argument, the code instead of giving a vector output, only gave the result of the first element.

Can somebody tell me how can I vectorize the output?


salaryCAl2 <- function(Years=1, Department){

  ifelse(Department=="Sales",Years * 10000 * 1.2,
 
         ifelse(Department == "Data", Years*12000*1.3, Years*13000*1.15))
}

y <- c(2,3)

salaryCAl2(y, "HR")

CodePudding user response:

Your function can be vectorized in many ways. One way is to create a function that calculates the salary for a single year, and the salaryCal2 apply this function to each year of the Years data.

salaryCAl2a<- function(Years=1, Department){
    single_year_cal <- function(ayear){
          
     ifelse(Department=="Sales",ayear * 10000 * 1.2,
     ifelse(Department == "Data", ayear*12000*1.3, ayear*13000*1.15))
     }
     
     unlist(lapply(Years, single_year_cal))
 }

salaryCAl2a(y, "HR")
#[1] 29900 44850

CodePudding user response:

You can use switch which is vectorized and is usually a better alternative for nested ifelse statements to handle different cases.

salaryCAl2 <- function(Years = 1, Department) {
  
  switch(
    Department,
    "Sales" = Years * 10000 * 1.2,
    "Data" = Years * 12000 * 1.3,
    Years * 13000 * 1.15
  )

}

y <- c(2,3)

salaryCAl2(y, "HR")

# [1] 29900 44850
  • Related