【问题标题】:Switch and if statement to be used togetherswitch 和 if 语句一起使用
【发布时间】:2020-01-10 05:02:52
【问题描述】:

我有一个包含性别列的数据框,其中包含男性和女性元素。还有一个名为 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


    【解决方案1】:

    如果打算基于 'gender' 中的值创建一个新列,请使用 mutate 中的 ifelsecase_when 创建列并将 (<-) 分配回输出到新的对象标识符或相同的对象

    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

    【讨论】:

    • 感谢您的回复。我们如何使用 if else 来解决问题
    • @RatneshKumar。正如我在帖子中提到的,不要使用if/else,而是使用ifelsecustomer %&gt;% mutate(new = ifelse(gender == 'Female', MonthlyCharges * 0.5, MonthlyCharges * 0.2))
    猜你喜欢
    • 2016-03-02
    • 2020-11-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-06-19
    相关资源
    最近更新 更多