An example of using let to wrap dplyr expressions as functions.
Note: let has been moved to the wrapr package.
The desired task: write a function that takes a data frame with a specified numerical column and an optional grouping column, and returns a data frame with one row per group containing:
The dplyr expression for such a table is easy when the column names are known, but complicated when they are not. We use wrapr::let to write such a function without the use of lazyeval or rlang/tidyeval.
sumstat_intervals = function(dframe, colname, groupcolname = NULL) {
mapping = list(COLNAME = colname,
GROUPCOLNAME = groupcolname)
let(alias = mapping,
{
if(!is.null(groupcolname)) {
dframe <- group_by(dframe, GROUPCOLNAME)
}
summarize(dframe,
sdlower = mean(COLNAME)-sd(COLNAME),
mean = mean(COLNAME),
sdupper = mean(COLNAME) + sd(COLNAME),
iqrlower = median(COLNAME)-0.5*IQR(COLNAME),
median = median(COLNAME),
iqrupper = median(COLNAME)+0.5*IQR(COLNAME))
})
}We can test sumstat_intervals on iris:
sumstat_intervals(iris, "Sepal.Length")
# sdlower mean sdupper iqrlower median iqrupper
# 1 5.015267 5.843333 6.671399 5.15 5.8 6.45