【发布时间】:2020-07-26 05:46:10
【问题描述】:
我正在阅读一些代码,需要确定所传递参数的参数名称。如果该人命名参数,我可以通过x[[param_name]] 找到它们。如果不明确,我如何找到它们?
在这个例子中,我试图找到“from”参数。我可以看到它是索引 #4,但它可能在位置 #2 或其他位置,并且它们中的任何一个或全部都可以是未命名的。
感谢您的宝贵时间。
x <- parse(text = "seq.int(to = 10, by = 2, 0)")
code_as_call <- as.call(x)[[1]]
View(code_as_call)
param_to <- code_as_call[["to"]]
param_by <- code_as_call[["by"]]
param_from <- "???" # how do I find this?
更新:
在@MichaelChirico 的帮助下,这是我想出的解决方案。我不得不考虑部分匹配作为一种选择。
arg_names <- function(x) {
x_fn <- x[[1]][[3]]
default_args <- c("", formalArgs(args(eval(x_fn[[1]]))))
missing_names <- is.null(names(x_fn))
seq_args <- seq_along(x_fn)
#skip_last <- head(seq_args, -1)
if (missing_names) {
# assign names after first position
names(x_fn) <- default_args[seq_args]
} else {
orig_args <- names(x_fn)
has_name <- nchar(orig_args) > 0
# line up args including partial matches
explicit_args <- pmatch(orig_args[has_name], default_args)
# update names
names(x_fn)[which(has_name)] <- default_args[explicit_args]
updated_args <- names(x_fn)
# missing args
avail_args <- setdiff(default_args, updated_args[has_name])
missing_name <- which(!has_name)
implicit_args <- avail_args[seq_along(missing_name)]
# update names
names(x_fn)[missing_name] <- implicit_args
}
names(x_fn)
}
arg_names(expression(new_string <- gsub(' ', '_', 'a b c')))
#> [1] "" "pattern" "replacement" "x"
arg_names(expression(new_string <- gsub(x = 'a b c', ' ', '_')))
#> [1] "" "x" "pattern" "replacement"
arg_names(expression(new_string <- gsub(x = 'a b c', pat = ' ', rep = '_')))
#> [1] "" "x" "pattern" "replacement"
由reprex package (v0.3.0) 于 2020 年 7 月 26 日创建
【问题讨论】: