0

I am trying to loop different variables into the same command:

Following is the list of variables and values I want to loop

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

Following is the command:

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

I am trying to loop

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) 

Is there an easier way to do this instead of copy and paste?

Oli
  • 9,766
  • 5
  • 25
  • 46

1 Answers1

0

You did not provide a reproducible example, so I will illustrate how to achieve what you want in dplyr for the mtcars data set:

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

Output

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

This should work in your case:

data_aliki %>% 
  group_by(indicator) %>%
  summarize_at(c("knocked1","questions1"),
               list("yes" = ~sum(. == 1, na.rm = TRUE),
                     "no" = ~sum(. == 0, na.rm = TRUE))
slava-kohut
  • 4,203
  • 1
  • 7
  • 24