首页 > 解决方案 > 编写函数以自动执行重复步骤的指南

问题描述

我正在尝试编写一个函数来自动执行我尝试采取的一系列步骤来重组和总结不同的变量,以便它们更容易可视化。不过,我编写自己的函数的经验有限,并且不确定我是否采取了正确的方法来做到这一点。我将不胜感激任何人可以提供的任何帮助,以帮助我使我的功能正常工作。

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)}}

标签: rdplyr

解决方案


推荐阅读