r - 如何在 dplyr %>% 运算符之后使用自定义函数?
问题描述
我想使用dplyr的自定义函数,所以我不必多次重复以下代码。
样本数据:
print(df)
Tran_Date Account Tran_Type Fee
1 2011-07-14 32-90-014846-00 <NA> 444.15
2 2011-09-01 32-90-014846-00 <NA> 117.79
3 2011-11-10 32-90-015611-00 <NA> 534.45
4 2012-01-12 90-015926-00 court costs 450.00
5 2012-02-09 90-015821-00 <NA> 640.25
6 2012-02-09 90-015128-00 <NA> 90.00
这是自定义函数:
State <- function(x, y){
mutate(`Account` = str_remove_all(`Account`, "-"),
Account = case_when(
startsWith(`Account`, y) ~ str_c(str_c("WC", x), `Policy #`),
startsWith(`Account`, x) ~ str_c("WC", `Policy #`)
))
}
df %>% State(32, 90)
Error in State(., x = 32, y = 90) : unused argument (.)
如何解决此错误,以便我可以使用管道操作员进行此操作,而不必一遍又一遍地重新使用功能代码?
谢谢!
解决方案
我调整了函数以包含数据框的参数,在函数定义中添加了必要的包,并将输入转换为字符而不是数字。如果需要,这也可以添加到函数定义中。
library(dplyr)
library(stringr)
State <- function(df, x, y){
dplyr::mutate(
df,
Account = stringr::str_remove_all(Account, "-"),
Account = case_when(
startsWith(Account, y) ~ stringr::str_c(stringr::str_c("WC", x), "Policy #"),
startsWith(Account, x) ~ stringr::str_c("WC", "Policy #")
)
)
}
df %>% State("32", "90")
推荐阅读
- javascript - PERMISSION_DENIED(为错误的数据库产品设置的规则)
- angular - 合并json对象
- amazon-web-services - 我们可以在不使用 Internet 网关的情况下设置 VPC 对等互连吗?
- ios - 水平条形图 Swift
- javascript - 如何通过 Haxe 放大从 ImageData 绘制到画布?
- java - Drools:drl 文件变量
- ms-access - Windows CE 应用程序 - Microsoft Access 数据库
- django - Block.objects.get(id=block_id, 1) 如果 id 为 null,则默认获取“1”
- javascript - 当用户在 textarea 唯一数据中输入时更改处理程序值
- validation - Android Databinding TextEdit Validation of two or more fields enable button