Suppose I have this code:
> df<-data.frame(a=c(1,1,1,2,2,2), b=c(T,T,F,F,F,T))
> df %>% group_by(a) %>% summarize(trues=sum(b), falses=sum(!b))
# A tibble: 2 x 3
a trues falses
<dbl> <int> <int>
1 1 2 1
2 2 1 2
and I want to use a string variable to give b (in a for loop, for example). It's exactly like this question I think, but I can't seem to get it to work.
Some failed attempts:
var <- 'b'
df %>% group_by(a) %>% summarize_(trues=sum(var), falses=sum(!var))
df %>% group_by(a) %>% summarize(trues=sum({{var}}), falses=sum(!{{var}}))
df %>% group_by(a) %>% summarize_(trues=sum({{var}}), falses=sum(!{{var}}))
foo1 <- function(df, var) {
df %>% group_by(a) %>% summarize(trues=sum({{var}}), falses=sum(!{{var}}))
}
foo1(df, 'b')
foo2 <- function(df, var) {
var <- enquo(var)
df %>% group_by(a) %>% summarize(trues=sum(!!var), falses=sum(! !!var))
}
foo2(df, 'b')
Perhaps I could use the lazyeval package in the other question, but I'd rather know how to do it with just the tidyverse.