Reputation: 2508
I have one dataset which contain two columns "Code" and "Gross_i". You can see data below:
# Data
TABLE<-data.frame(Code=as.integer(c("1","2","3","4","5")),
Gross_i=as.integer(c("10","20","30","40","50")
))
TAX_RATE1<-0.20
TAX_RATE2<-0.25
My intention here is to multiply second column "Gross_i" with two different tax rates.So I need to multiply first three code "1","2" and "3" with TAX_RATE1 (20%) and observation "4" and "5" with TAX_RATE2 (25%). In order to do this I try this line of code (If else statment) but results are not good:
pit_1=if_else(filter(Code %in% c("1","2","3")),Gross_i*TAX_RATE1,Gross_i*TAX_RATE2)
So can anybody help how to fix this line of code?
Upvotes: 0
Views: 57
Reputation: 4417
Your attempt at if_else
translates easily to the following using ifelse
pit_1 <- ifelse(TABLE$Code %in% c("1", "2", "3"),
yes = TABLE$Gross_i * TAX_RATE1,
no = TABLE$Gross_i * TAX_RATE2)
Upvotes: 0
Reputation: 388817
If you have only two tax rates, you can do :
library(dplyr)
TABLE %>% mutate(pit_1 = Gross_i * c(TAX_RATE2, TAX_RATE1)[(Code %in% 1:3) + 1])
# Code Gross_i pit_1
#1 1 10 2.0
#2 2 20 4.0
#3 3 30 6.0
#4 4 40 10.0
#5 5 50 12.5
If you lot of rates like this it would be easy to specify conditions within case_when
:
TABLE %>%
mutate(pit_1 = Gross_i * case_when(Code %in% 1:3 ~ TAX_RATE1,
TRUE ~ TAX_RATE2))
Upvotes: 2
Reputation: 39585
This approach can be useful with dplyr
in the field:
library(dplyr)
#Code
TABLE %>% mutate(Value=if_else(Code %in% c("1","2","3"),Gross_i*TAX_RATE1,Gross_i*TAX_RATE2))
Output:
Code Gross_i Value
1 1 10 2.0
2 2 20 4.0
3 3 30 6.0
4 4 40 10.0
5 5 50 12.5
Upvotes: 1