如何使用srvyr包中的函数编写包含管道的函数?

如何使用srvyr包中的函数编写包含管道的函数?,r,pipe,R,Pipe,我有一项调查,我正试图按年份进行分组,并计算某些变量的总数。我需要用不同的变量做大约20次,所以我正在编写一个函数,但我似乎无法正常工作,即使它在函数之外工作得很好 这很好: mepsdsgn %>% group_by(YEAR) %>% summarise(tot_pri = survey_total(TOTPRV)) %>% select(YEAR, tot_pri) 当我尝试一个函数时: total_calc <- function(x) {mepsdsgn %

我有一项调查,我正试图按年份进行分组,并计算某些变量的总数。我需要用不同的变量做大约20次,所以我正在编写一个函数,但我似乎无法正常工作,即使它在函数之外工作得很好

这很好:

 mepsdsgn %>% group_by(YEAR) %>% summarise(tot_pri = survey_total(TOTPRV)) %>% select(YEAR, tot_pri)
当我尝试一个函数时:

total_calc <- function(x) {mepsdsgn %>% group_by(YEAR) %>% summarise(total = survey_total(x)) %>% select(YEAR, total)}

total_calc(TOTPRV)
total_calc%group_by(YEAR)%%>%summary(total=survey_total(x))%%>%select(YEAR,total)}
总计算(总价值)

我得到这个错误:停止因子(x)中的错误:未找到对象“TOTPRV”

我建议做几件事,见下文

# first try to make a working minimal example people can run in a new R session
library(magrittr)
library(dplyr)
dt <- data.frame(y=1:10, x=rep(letters[1:2], each=5))

# simple group and mean using the column names explicitly
dt %>% group_by(x) %>% summarise(mean(y))

# a bit of googling showed me you need to use group_by_at(vars("x")) to replicate
# using a string input
# in this function, add all arguments, so the data you use - dt & the column name - column.x
foo <- function(dt, column.x){
  dt %>% group_by_at(vars(column.x)) %>% summarise(mean(y))
}

# when running a function, you need to supply the name of the column as a string, e.g. "x" not x
foo(dt, column.x="x")
#首先尝试制作一个人们可以在新的R会话中运行的最简单的示例
图书馆(magrittr)
图书馆(dplyr)
dt%组(x)%>%总结(平均值(y))
#通过谷歌搜索,我发现你需要使用groupbyat(vars(“x”)进行复制
#使用字符串输入
#在这个函数中,添加所有参数,使您使用的数据-dt&列名-column.x
foo%分组(变量(第x列))%>%汇总(平均值(y))
}
#运行函数时,需要以字符串形式提供列的名称,例如“x”而不是“x”
foo(dt,column.x=“x”)
我不使用dplyr,所以可能有更好的方法来解决这个问题:

总计%group(年度)%%>%总结(总计=调查总计(!!sym(col),na.rm=TRUE))%%>%选择(年度,总计)
}

TOTPRV是某个对象的名称(字符串,如变量名称)还是实际对象?它是dataframe MEPSDSGN中的一个列名那么调用函数时应该将其作为字符串引用。。。。这是问题一,解决它。然后,您可以在函数中将其称为
mepsdsgn[[x]]]
总计(年度)%>%summary(tot=调查总计(mepsdsgn[[x]])%>%select(YEAR,tot)}总计(mepsdsgn[[TOTPRV]]``和
总计(年度)%>%summary(tot=调查总计(x))%>%select(YEAR,tot)}总计)}
这两个程序仍然会在stop_中得到错误,因为_因子(x):未找到对象“TOTPRV”。我认为这可以解决问题,但程序包是sryvr,而不是dplyr