【问题标题】:Pass arguments into function within a function将参数传递给函数内的函数
【发布时间】:2012-06-19 19:17:49
【问题描述】:

我正在编写函数,该函数涉及来自基本 R 的其他函数,并带有很多参数。例如(实际函数要长得多):

myfunction <- function (dataframe, Colv = NA) { 
matrix <- as.matrix (dataframe) 
out <- heatmap(matrix, Colv = Colv)
return(out)
}

data(mtcars)

myfunction (mtcars, Colv = NA)

热图有许多可以传递给的参数:

heatmap(x, Rowv=NULL, Colv=if(symm)"Rowv" else NULL,
        distfun = dist, hclustfun = hclust,
        reorderfun = function(d,w) reorder(d,w),
        add.expr, symm = FALSE, revC = identical(Colv, "Rowv"),
        scale=c("row", "column", "none"), na.rm = TRUE,
        margins = c(5, 5), ColSideColors, RowSideColors,
        cexRow = 0.2 + 1/log10(nr), cexCol = 0.2 + 1/log10(nc),
        labRow = NULL, labCol = NULL, main = NULL,
        xlab = NULL, ylab = NULL,
        keep.dendro = FALSE, verbose = getOption("verbose"), ...)

我想使用这些参数而不在 myfunction 中列出它们。

myfunction (mtcars, Colv = NA, col = topo.colors(16))
Error in myfunction(mtcars, Colv = NA, col = topo.colors(16)) : 
  unused argument(s) (col = topo.colors(16))

我尝试了以下方法但不起作用:

myfunction <- function (dataframe, Colv = NA) { 
matrix <- as.matrix (dataframe) 
out <- heatmap(matrix, Colv = Colv, ....)
return(out)
}
data(mtcars)

myfunction (mtcars, Colv = NA, col = topo.colors(16))

【问题讨论】:

    标签: r function arguments


    【解决方案1】:

    尝试三个点而不是四个点,并将省略号参数添加到顶级函数:

    myfunction <- function (dataframe, Colv = NA, ...) { 
        matrix <- as.matrix (dataframe) 
        out <- heatmap(matrix, Colv = Colv, ...)
        return(out)
    }
    

    【讨论】:

    • 只是为了添加一个选项(或添加混淆),您可以通过在主函数dotfuns&lt;-list(..., other_variable) 中设置一个变量并将其传递给后续函数来增加... 的内容。这样做需要您自担风险:-)
    • @CarlWitthoft 抱歉,我无法理解您的意思,可以扩展您的解决方案(也许作为答案)
    • 这不是针对您的具体问题的答案,只是对... 参数集合可以完成的其他事情的评论。
    • 这个答案很有帮助,我想知道当你有2个不同的函数具有不同的参数名称时是否有解决方案
    猜你喜欢
    • 1970-01-01
    • 2018-09-26
    • 2013-01-27
    • 2011-03-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 2015-02-17
    • 1970-01-01
    相关资源
    最近更新 更多