Skip to content

Instantly share code, notes, and snippets.

@peterhurford
Last active May 31, 2017 02:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save peterhurford/1702461c45138cad033f to your computer and use it in GitHub Desktop.
Save peterhurford/1702461c45138cad033f to your computer and use it in GitHub Desktop.
#' Calculate a dep_var for the iris dataset based on the iris dataset.
#'
#' @param by character. \code{length} to go by \code{Petal.Length} or \code{width} to go by \code{Petal.Width}.
iris_with_dep_var <- validations::ensure(pre = list(by %in% c("length", "width")),
  function(by = "length") {
    if (identical(by, "length")) {
      plyr::ddply(iris, plyr::.(Species), summarize, dep_var = ifelse(any(Petal.Length >= 4), 1, 0))
    } else {
      plyr::ddply(iris, plyr::.(Species), summarize, dep_var = ifelse(any(Petal.Width >= 4), 1, 0))
    }})

First attempt at DRY:

#' Calculate a dep_var for the iris dataset based on the iris dataset.
#'
#' @param by character. \code{length} to go by \code{Petal.Length} or \code{width} to go by \code{Petal.Width}.
iris_with_dep_var <- validations::ensure(pre = list(by %in% c("length", "width")),
  function(by = "length") {
    plyr::ddply(iris, plyr::.(Species), summarize, dep_var =
      ifelse(any(if ((identical(by, "length"))) { Petal.Length } else { Petal.Width }) >= 4), 1, 0)
  })

Second attempt:

iris_with_dep_var <- validations::ensure(pre = list(by %in% c("length", "width")),
  function(by = "length") {
    var <- if (identical(by, "length")) { "Petal.Length" } else { "Petal.Width" }
    plyr::ddply(iris, plyr::.(Species), summarize, dep_var = ifelse(any(as.name(var) >= 4), 1, 0))
  })

...or (not as good)

iris_with_dep_var <- validations::ensure(pre = list(by %in% c("length", "width")),
  function(by = "length") {
    plyr::ddply(iris, plyr::.(Species), summarize, dep_var = ifelse(any(
      if (identical(by, "length")) { quote(Petal.Length) } else { quote(Petal.Width) } >= 4), 1, 0))
  })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment