Skip to content

Instantly share code, notes, and snippets.

@TimTaylor
Last active February 24, 2021 04:11
Show Gist options
  • Save TimTaylor/b9deeb9d6babb82a8a1beb9afba42a92 to your computer and use it in GitHub Desktop.
Save TimTaylor/b9deeb9d6babb82a8a1beb9afba42a92 to your computer and use it in GitHub Desktop.
return quoted arguments of given expression
# Based on this stackoverflow answer (https://stackoverflow.com/a/57709169)
# from Valeri Voev
#' Return quoted arguments of given expression
#'
#' @param args Expression such `x`, `"x"`, `c(x, y)` or `c("x", "y")`.
#'
#' @return The quoted arguments.
#'
#' @examples
#' return_args(x)
#' return_args("x")
#' return_args(c(x, y))
#' return_args(c("x", "y"))
#'
#' @noRd
return_args <- function(args) {
args_expr <- enexpr(args)
if(length(args_expr) == 1) {
args_vars <- as.list(args_expr)
} else {
args_vars <- as.list(args_expr)[-1]
}
vapply(args_vars, quo_name, character(1))
}
#' Return names of arguments of given expression
#'
#' @param args Expression such `c(a = x, b = y)` or `c(x, y)`.
#'
#' @return The arguments names if they exist.
#'
#' @examples
#' return_args(c(a = x, b = y))
#' return_args(c(a = x, y))
#' @noRd
return_args_names <- function(args) {
expr <- rlang::enexpr(args)
names(return_args(!!expr))
}
# Example use 1
myfun <- function(counts) {
counts <- rlang::enquo(counts)
expr <- rlang::quo_get_expr(counts)
arg_v <- return_args(!!expr)
arg_n <- return_args_names(!!expr)
if (!is.null(arg_v)) {
cat("Argument values:\n")
print(arg_v)
}
if (!is.null(arg_n)) {
cat("Argument names:\n")
print(arg_n)
}
}
# Example use 2
myfun2 <- function(counts) {
counts <- rlang::enquo(counts)
expr <- rlang::quo_get_expr(counts)
arg_v <- return_args(!!expr)
arg_n <- names(arg_v)
if (!is.null(arg_v)) {
cat("Argument values:\n")
print(arg_v)
}
if (!is.null(arg_n)) {
cat("Argument names:\n")
print(arg_n)
}
}
myfun(x)
myfun("x")
myfun(c(nm1 = x, nm2 = y))
myfun(c(nm1 = x, y))
myfun2(x)
myfun2("x")
myfun2(c(nm1 = x, nm2 = y))
myfun2(c(nm1 = x, y))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment