Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
dplyr%>;%之后如何使用自定义函数操作人员_R_Dplyr - Fatal编程技术网

dplyr%>;%之后如何使用自定义函数操作人员

dplyr%>;%之后如何使用自定义函数操作人员,r,dplyr,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&g

我想在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
打印(df)
交易日期账户交易类型费
1 2011-07-14 32-90-014846-00         444.15
2 2011-09-01 32-90-014846-00         117.79
3 2011-11-10 32-90-015611-00         534.45
4 2012-01-12 90-015926-00法庭费用450.00
5 2012-02-09    90-015821-00         640.25
6 2012-02-09    90-015128-00          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 (.)
State%状态(32,90)
状态错误(,x=32,y=90):未使用的参数(.)
如何解决此错误,以便可以使用管道操作符执行此操作,而无需反复使用函数代码


谢谢

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

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")
库(dplyr)
图书馆(stringr)
州%州(“32”、“90”)

您需要数据对象%>%运算符从左侧获取一个数据帧,并将其传递给右侧函数的第一个参数。State()不接受数据帧,因此需要使用数据帧作为第一个参数重新定义Stata()。