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

时间:2019-11-20 15:45:14

标签: r dataframe summarize

我试图将不同的变量循环到同一命令中:

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

// If left subtree is not empty, print left subtree 
int lsize = root;
if (lsize != 0) 
  printPostOrder(
    Arrays.copyOfRange(in1, 0, lsize),
    Arrays.copyOfRange(pre, 1, lsize),
    lsize);

// If right subtree is not empty, print right subtree 
int rsize = n - root - 1;
if (rsize != 0) 
  printPostOrder(
    Arrays.copyOfRange(in1, root + 1, rsize),
    Arrays.copyOfRange(pre, root + 1, rsize),
    rsize);

以下是命令:

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

有比复制和粘贴更简单的方法吗?

1 个答案:

答案 0 :(得分:0)

您没有提供可复制的示例,因此我将说明如何针对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))