Reputation: 436
There is a data.frame like so:
df <- data.frame("Config" = c("C1","C1","C2","C2"), "SN1" = 1:4, "SN2" = 5:8)
I'm trying to make group_by %>% summarise
more generic. Here is an example that does not work:
variable <- "SN1"
df %>%
group_by(
Config
) %>%
summarise(
paste0(variable, ".median")=median(UQ(as.symbol(variable)))
) %>%
as.data.frame() ->
df_summary
It does not work because of paste0(variable, ".median")
part.
Related question-answer Pass arguments to dplyr functions helped me to parameterize median(UQ(as.symbol(variable)))
part but it does not mention the left-hand side part.
Is there a way to fix the above?
Upvotes: 0
Views: 93
Reputation: 28705
You can use enquo
and !!
library(tidyverse)
mysumm <- function(variable){
var <- enquo(variable)
df %>%
group_by(
Config
) %>%
summarise(!!paste0(variable, ".median") := median(!!var))
}
mysumm('SN1')
# # A tibble: 2 x 2
# Config SN1.median
# <fct> <chr>
# 1 C1 SN1
# 2 C2 SN1
Upvotes: 3