如何将不同的变量循环到同一个命令

How can I loop different variables to the same command

我正在尝试将不同的变量循环到同一个命令中:

以下是我要循环的变量和值的列表

behavior_list <- c("knocked1", "questions1", ...)
answer_list <- c(0, 1)
answer_label_list <- c("Yes", "No")

命令如下:

data_aliki %>% 
  group_by(indicator) %>%
  summarise(
    total_indicator = n(),
    yes_knocked1 = sum(knocked1==1, na.rm = TRUE)
  )

我正在尝试循环

yes_knocked1 = sum(knocked1==1, na.rm = TRUE) 
no_knocked1 = sum(knocked1==0, na.rm = TRUE)
yes_questions1 = sum(questions1==1, na.rm = TRUE) 
no_questions1 = sum(questions1==0, na.rm = TRUE) 

除了复制和粘贴之外,还有更简单的方法吗?

您没有提供可重现的示例,所以我将说明如何在 dplyr 中针对 mtcars 数据集实现您想要的:

  mtcars %>% group_by(cyl) %>%
  summarize_at(c("mpg","hp"), list("lt15" = ~sum(. < 15, na.rm = TRUE),
                              "lt18" = ~sum(. < 18, na.rm = TRUE)))

输出

cyl mpg_lt15 hp_lt15 mpg_lt18 hp_lt18
  <dbl>    <int>   <int>    <int>   <int>
1     4        0       0        0       0
2     6        0       0        1       0
3     8        5       0       12       0

这应该适用于您的情况:

data_aliki %>% 
  group_by(indicator) %>%
  summarize_at(c("knocked1","questions1"),
               list("yes" = ~sum(. == 1, na.rm = TRUE),
                     "no" = ~sum(. == 0, na.rm = TRUE))