我进行了一项调查,试图将其按年份分组并计算某些变量的总计。我需要使用不同的变量执行此操作大约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)
我收到此错误:stop_for_factor(x)中的错误:找不到对象“ TOTPRV”
答案 0 :(得分:1)
弄清楚了:
total_fun <-function(x){ col = x mepsdsgn%>%group_by(YEAR)%>%摘要(total = survey_total(!! sym(col),na.rm = TRUE))%>%select(YEAR,total) }
答案 1 :(得分:0)
我建议您做几件事,请参见下文
index.js
我不使用# 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")
,所以可能会有更好的方法