首页 > 解决方案 > 如何在 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 (.)

如何解决此错误,以便我可以使用管道操作员进行此操作,而不必一遍又一遍地重新使用功能代码?

谢谢!

标签: rdplyr

解决方案


我调整了函数以包含数据框的参数,在函数定义中添加了必要的包,并将输入转换为字符而不是数字。如果需要,这也可以添加到函数定义中。

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")

推荐阅读