#' 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))
})