我想将自定义函数与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")
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句