r - 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)}
解决方案
如果打算基于“性别”中的值创建一个新列,请使用ifelse
或case_when
inmutate
创建该列并将<-
输出分配 ( ) 回一个新的对象标识符或相同的对象
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
推荐阅读
- r - 使用两个向量作为指示符折叠行
- python - 在python中访问另一个类的方法
- django - 在 Python 中重构 try 和 except 代码块
- css - angularjs中的警报对话框导致页面滚动到顶部
- mongodb - 如何使用 Golang 和 MongoDriver 解决“命令查找需要身份验证”
- xslt-1.0 - 将模板应用于其兄弟元素具有特定属性值的元素
- javascript - Angular7,获取 ElementRef
- r - 收集高程数据 - 从 geotiff 文件中提取地理位置
- spring-boot - 为什么在交换访问令牌的授权码时收到无效的令牌响应?(弹簧靴,oauth2,天蓝色)
- asp.net-web-api - 使用特定列表以角度检索数据