[英]Combine if else statement with two conditions
I have one dataset which contain two columns "Code" and "Gross_i".我有一个数据集,其中包含两列“代码”和“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%).我的目的是将第二列“Gross_i”与两个不同的税率相乘。所以我需要将前三个代码“1”、“2”和“3”与 TAX_RATE1(20%)和观察“4”和“5”相乘" 与 TAX_RATE2 (25%)。 In order to do this I try this line of code (If else statment) but results are not good:
为了做到这一点,我尝试了这行代码(If else 语句),但结果并不好:
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?那么有人可以帮助如何修复这行代码吗?
This approach can be useful with dplyr
in the field:这种方法在现场对
dplyr
很有用:
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
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
:如果您有很多这样的费率,则很容易在
case_when
指定条件:
TABLE %>%
mutate(pit_1 = Gross_i * case_when(Code %in% 1:3 ~ TAX_RATE1,
TRUE ~ TAX_RATE2))
Your attempt at if_else
translates easily to the following using ifelse
您对
if_else
尝试使用ifelse
可以轻松转换为以下ifelse
pit_1 <- ifelse(TABLE$Code %in% c("1", "2", "3"),
yes = TABLE$Gross_i * TAX_RATE1,
no = TABLE$Gross_i * TAX_RATE2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.