R 当我';我已经在用省略号了?

R 当我';我已经在用省略号了?,r,R,我有一个这样的函数来检索项目 fetchItem <- function(name, ..., FUN) fetchItem为了说明我在上面最后一条评论中的观点,像这样的东西怎么样 do_something <- function(x, ..., FUN = NULL) { if (is.null(FUN)) print(x) # Get all additional arguments args <- list(...) # Match

我有一个这样的函数来检索项目

fetchItem <- function(name, ..., FUN)

fetchItem为了说明我在上面最后一条评论中的观点,像这样的东西怎么样

do_something <- function(x, ..., FUN = NULL) {
    if (is.null(FUN)) print(x)

    # Get all additional arguments
    args <- list(...)

    # Match additional arguments that are allowed for FUN
    args_for_FUN <- NULL
    if (length(args) > 0) {
        allowed_args_for_FUN = c("na.rm")

        # Allow for partial matching
        names(args) <- sapply(names(args), function(arg)
            match.arg(arg, allowed_args_for_FUN))
        args_for_FUN <- args[names(args) %in% allowed_args_for_FUN]

    }

    # Execute FUN (if given)
    if (is.function(FUN)) do.call(FUN, c(list(x = x), args_for_FUN))
}
虽然我可以设想这可能会有问题,但有一种技巧可以是为了一个目的使用所有未命名的参数,并要求所有
FUN
参数都显式命名

过度简化了使用
只是将其连接到一个文件路径:


fetchItem能否将
FUN\u args
参数添加到
fetchItem
,该参数包含
FUN
的任何附加参数?然后,您需要解析
FUN_args
来提取
FUN
@Maurits Evers的相关参数。我认为这可能会起作用,但我想知道是否有一种更优雅的方法可以将这些参数传递给FUN解析的对象。另一种方法是解析所有其他参数,然后特别决定是否传递一个参数参数是否为
FUN
。我想这不会太难,只要你有一个
FUN
的允许参数列表,你可以与之匹配。snappymcsnap,其中一个答案解决了你的问题吗?
# Case 1: No FUN, no additional args
do_something(1:10)
# [1]  1  2  3  4  5  6  7  8  9 10

# Case 2: With FUN, no additional args
do_something(1:10, FUN = mean)
#[1] 5.5

# Case 3: With FUN, no additional args
do_something(c(1:10, NA), FUN = mean)
#[1] NA

# Case 4: With FUN, with an additional arg for FUN
do_something(c(1:10, NA), na.rm = T, FUN = mean)
#[1] 5.5