首页 > 解决方案 > switch 和 if 语句一起使用

问题描述

我有一个数据框,其中包含一个性别列,其中包含男性和女性元素。还有一个名为 Total Charges 的列。

我想在新列中计算税收。如果性别是男性,税率为 20%,如果是女性,则税率为 15%。

我正在使用下面提到的代码,但给出了错误的答案。谁能帮忙

x=customer[ ,"gender"] %>% 
 if(x=="Female"){
   print (customer[ , "MonthlyCharges"]*0.50)
      } else {
      print(customer[ , "MonthlyCharges"]*0.20)
   }  "MonthlyCharges"]*0.20)}

标签: r

解决方案


如果打算基于“性别”中的值创建一个新列,请使用ifelsecase_wheninmutate创建该列并将<-输出分配 ( ) 回一个新的对象标识符或相同的对象

library(dplyr)
customer <- customer  %>%
          mutate(new = case_when(gender == "Female" ~ MonthyCharges * 0.5,  
                  TRUE ~ MonthlyCharges * 0.2))

OP 的代码中有多个问题。

1)base R使用 tidyverse 的混合方法

2)使用print而不是返回值

3) if/else 代替 ifelse 因为元素的数量大于 1


推荐阅读