If and multiple conditions

Hello, I'm stuck with this code.

I want that if My_Data $ Tax> 10 million a new variable is created that multiplies My_Data$Tax by 7%.
If My_Data $ Tax is between 9.9M and 4M, the variable that is created is the value of My_Data$Tax multiplied by 4.5%.
If My_Data$Tax is between 3.9M and 2M, the variable that is created is the value of My_Data$Tax multiplied by 2.5%
Thus until reaching the case in which My_Data$Tax is less than 0.5M when the new variable would register the value of My_Data$Tax multiplied by 0.5%

The message I get says: the condition has length> 1 and only the first element will be used

This is my code

if(My_Data$Tax >= 10000000){
  My_Data$New_VAR<- My_Data$VAR1 * 0.07
}else if(My_Data$Tax <= 9999999 & My_Data$Tax >= 4000000){
  My_Data$New_VAR <- My_Data$Tax * 0.45
}else if(My_Data$Tax <= 3999999 & My_Data$Tax >= 2000000){
  My_Data$New_VAR <- My_Data$Tax * 0.25
}else if(My_Data$Tax <=1999999 & My_Data$Tax >=1000000){
  My_Data$New_VAR <- My_Data$Tax * 0.15
}else if(My_Data$Tax <=999999 & My_Data$Tax >=500000){
  My_Data$New_VAR <- My_Data$Tax * 0.1
}else{
  My_Data$New_VAR <- My_Data$Tax * 0.05
}

if can only test single values, to process a whole vector value by value use the vectorised ifelse function

I think what you're looking for is case_when! Which would go something like:

library(tidyverse)
My_Data %>%
  mutate(New_VAR = case_when(
    Tax>=10000000 ~ Tax*0.7,
    Tax<=9999999 & Tax>=4000000 ~ Tax*0.45,
    Tax<=3999999 & Tax>=2000000 ~ Tax*0.25,
    Tax<=1999999 & Tax>=1000000 ~ Tax*0.15,
    Tax<=999999 & Tax>=500000 ~ Tax*0.1,
    Tax<=499999 ~ Tax*0.05,
    TRUE ~ Tax))

(I changed the tax bracket of your millionaires, by the way--just making the socialist assumption you'd rather them taxed at 70% and not 7%).

2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.