Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

check_names() case study #79

Open
hadley opened this issue May 23, 2019 · 0 comments
Open

check_names() case study #79

hadley opened this issue May 23, 2019 · 0 comments

Comments

@hadley
Copy link
Member

@hadley hadley commented May 23, 2019

# Use early returns to minimse code
check_names_1 <- function(names, x) {
  if (rlang::is_formula(names)) {
    names <- rlang::as_function(names)
  }
  if (is.function(names)) {
    names <- names(base::names(x))
  }

  vec_assert(names, ptype = character(), size = length(x))
  names
}


# Emphasise three types of input
check_names_2 <- function(names, x) {
  if (is.null(names)) {
    names
  } else if (is.function(names) || rlang::is_formula(names)) {
    fun <- rlang::as_function(names)
    names <- fun(base::names(x))
    vec_assert(names, ptype = character(), size = length(x))
  } else if (is.vector(names)) {
    vec_assert(names, ptype = character(), size = length(x))  
  } else {
    rlang::abort("`names` must be NULL, a function (or formula), or a vector")
  }
}


check_names_2.5 <- function(names, x) {
  if (is.null(names)) {
    names
  } else if (vec_is(names)) {
    vec_assert(names, ptype = character(), size = length(x))  
  } else if (rlang::is.formula(names)) {
    check_names_2(rlang::as_function(names), x)
  } else if (is.function(names)) {
    check_names_2(names(x), x)
  } else {
    rlang::abort("`names` must be NULL, a function or formula, or a vector")
  }
}

# Use a generic
check_names_3 <- function(names, x) UseMethod("check_names_3")
check_names_3.NULL <- function(names, x) NULL
check_names_3.character <- function(names, x) {
  if (length(names) != length(x)) {
    stop("`names` and `x` must be the same length", call. = FALSE)
  }
  names
}
check_names_3.formula <- function(names, x) check_names_3(rlang::as_function(names), x)
check_names_3.function <- function(names, x) check_names_3(names(base::names(x)), x)
check_names_3.default <- function(names, x) stop("Invalid input to names (", class(names)[[1]] ,")")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant