编写自动执行重复步骤的功能的指南

时间:2019-06-21 20:13:56

标签: r dplyr

我正在尝试编写一个函数,该函数可以使我尝试采取的一系列步骤自动化,以重组和汇总不同的变量,从而使它们更易于可视化。但是,我在编写自己的函数方面经验有限,并且不确定是否采用正确的方法来执行此操作。任何人都可以提供帮助以使我的功能正常工作,我将不胜感激。

agent_data_clean是我正在使用的数据框架,其余名称是数据框架中的变量名称。

这是我要自动化的代码:

agent_col_names <- c("region", "Impression", "code", "counts", "question")

agent_q2a <- agent_data_clean %>% group_by(region, Impression, `The 
formal training you received in EDGE`) %>% summarise(counts = n()) 
%>% mutate(question = "The formal training you 
received in EDGE")

colnames(agent_q2a) <- agent_col_names

agent_q2b <- agent_data_clean %>% group_by(region, Impression, `The in- 
person, instructor-led training`) %>%
summarise(counts = n()) %>% mutate(question = "The in-person, instructor- 
led training")

colnames(agent_q2b) <- agent_col_names

agent_q2c <- agent_data_clean %>% group_by(region, Impression, `The E- 
learning training (GU Courses)`) %>%
summarise(counts = n()) %>% mutate(question = "The E-learning training 
(GU Courses)")

colnames(agent_q2c) <- agent_col_names

agent_q2 <- bind_rows(agent_q2a, agent_q2b, agent_q2c)

这是我试图使上述步骤自动化的功能的副本:

test <- function(df, grp_constant, grp_vars, col_names) {
for(i in seq_along(grp_vars)) {
result <- list()
grp[i] <- c(grp_constant, grp_vars)
result$agent_q[i] <- df %>% group_by(grp[i]) %>% summarise(counts = n()) 
%>% mutate(question = as.character(grp_vars[i]))
colnames(agent_q[i]) <- col_names
return(result)}}

0 个答案:

没有答案