DavidF
DavidF

Reputation: 91

tidyverse user defined function variable usage

I need some help understanding how tidyverse variables work inside functions. I thought all I needed to do was to embrace the variable with {{ }}, but it doesn't work as expected. See below:


savings <- c(rep(10,5),rep(20,5))
state <- c(rep("A",5),rep("B",5))

fundata <- tibble(state, savings)

# this works

fundata %>% 
  group_by(state) %>% 
  summarize(savings1 = sum(savings))

# this doesnt, calcs ignore group by 

savepct_t <- function(split) {
  split %>%
    group_by({{state}}) %>%
    summarize(savings1 = sum({{savings}}))
}
savepct_t(fundata)

# this also works

savepct_t1 <- function(split) {
  split %>%
    group_by(.data$state) %>%
    summarize(savings1 = sum(.data$savings))
}
savepct_t1(fundata)


I am using the third approach, and it is working, but I don't understand why the second approach does not. Any insight would be appreciated.

Thanks,

David

Upvotes: 0

Views: 467

Answers (1)

Waldi
Waldi

Reputation: 41260

{{}} is used for non-standard evaluation, for example if you want to pass the group and the variable to the function:

savepct_t <- function(split,group,what) {
  split %>%
    group_by({{group}}) %>%
    summarize(result = sum({{what}}))
}

savepct_t(fundata,state,savings)

# A tibble: 2 x 2
  state   result
  <chr>    <dbl>
1 A          150
2 B          150

Upvotes: 2

Related Questions