Reputation: 71
I have dataframe df
as follows:
df <- data.frame(x = c("A", "A", "B", "B"), y = 1:4)
And I have a function that finds the mean of y
grouped by x
:
generateVarMean <- function(df, x, y) {
mean.df <- df %>%
select(x, y) %>%
group_by(x) %>%
dplyr::summarise(variable.mean = mean(y, na.rm = TRUE))
colnames(mean.df)[2] <- paste0("y", ".mean")
print(mean.df)
}
However, I want to the first argument of paste0()
to reflect the actual function argument (i.e. so that it can be used for different dataframes).
Desired functionality:
df1 <- data.frame(a = c("A", "A", "B", "B"), b = 1:4)
generateVarMean(df1, a, b)
a b.mean
1 A 1.5
2 B 3.5
Any help getting pointed in the right direction very much appreciated.
Upvotes: 2
Views: 99
Reputation: 1709
No need to add anything to the function. Just replace paste0("y", ".mean")
with paste0(deparse(substitute(y)), ".mean")
So now the function and the output will be:
> generateVarMean <- function(df, x, y) {
mean.df <- df %>%
select(x, y) %>%
group_by(x) %>%
dplyr::summarise(variable.mean = mean(y, na.rm = TRUE))
colnames(mean.df)[2] <- paste0(deparse(substitute(y)), ".mean")
print(mean.df)
}
> generateVarMean(df, a, b)
# A tibble: 2 × 2
x b.mean
<fctr> <dbl>
1 A 1.5
2 B 3.5
Upvotes: 1
Reputation: 887531
We can make use of the quosure
from the devel version of dplyr
(soon to be released 0.6.0
)
generateVarMean <- function(df, x, y) {
x <- enquo(x)
y <- enquo(y)
newName <- paste0(quo_name(y), ".mean")
df %>%
select(UQ(x), UQ(y)) %>%
group_by(UQ(x)) %>%
summarise(UQ(newName) := mean(UQ(y), na.rm = TRUE))
}
generateVarMean(df1, a, b)
# A tibble: 2 × 2
# a b.mean
# <fctr> <dbl>
#1 A 1.5
#2 B 3.5
We get the input arguments as quosure
with enquo
, convert the quosure to string with quo_name
to create 'newName' string. Then, evaluate the quosure
inside select/group_by/summarise
by unquoting (UQ
or !!
). Note that in the new version, we can also assign the column names directly and using the assign operator (:=
)
Upvotes: 2