I am trying to find a R function which can implement the functionality of "count" and "case when" in sql. Simple example could be as follows:
I have a data frame
df <- data.frame(flag=c("pos","neg","pos"),rule=c("Strict","Lenient","Strict"))
> df
flag rule
1 pos Strict
2 neg Lenient
3 pos Strict
I want the output to be
rule Positive_flag Negative_flag
Strict 2 0
Lenient 0 1
I am basically creating two new variables based on the count of positive and negative flag.
I can do this in sql using
select sum(case when flag = "pos" then 1 else 0 end) as Positive_flag, sum(case when flag = "neg" then 1 else 0 end) as Negative_flag group by rule;
What will be the R equivalent function for this