let Example

knitr::opts_chunk$set(
  collapse = TRUE,
  comment = " # ",
  fig.width = 7
)
options(width =100)

An example of using let to wrap dplyr expressions as functions.

Note: let has been moved to the wrapr package.

library("dplyr")
library("replyr")

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")
sumstat_intervals(iris, "Sepal.Length", "Species")
sumstat_intervals(iris, "Petal.Length", "Species")


Try the replyr package in your browser

Any scripts or data that you put into this service are public.

replyr documentation built on Nov. 1, 2019, 7:49 p.m.