I am using a simple command with dyplr to first filter a dataframe by two columns and then report the sum of another column. However I would like to create a loop so that the filtering criteria can be automated by a list of values. For example the code for a single instance:
library(dplyr)
df = data.frame(Category1 = sample(c("FilterMe","DoNotFilterMe"), 15, replace=TRUE),
Category2 = sample(c("1","3","5","10"),15, replace=TRUE),
Value = 1:15)
df %>%
filter(Category1=="FilterMe" & Category2="1") %>%
summarize(result=sum(Value))
This works perfectly and I get a single value of 15. However I would like to loop the command such that I can do multiple values for Category2 defined by a list of integers (not sequential). I want it to loop for each value of i and provide a different output value each time. I tried the code below but was left with a null value.
library(dplyr)
for (i in c(1,3,5,10){
df %>%
filter(Category1=="FilterMe" & Category2="i") %>%
summarize(result=sum(Value))}
If there is another way besides loop that would fulfill the same objective that is fine by me.