首页 > 解决方案 > R:在应用于特定对象时获取函数的形式参数

问题描述

假设我有一个函数 f(x) 应用于数据对象 x。我需要知道 f 是否有某个论点,准确地说是一个“na.rm”论点。我可以通过调用 names(formals(f)) 来找出答案,但是 f 作为一个完全通用的函数,可能有多种方法(S3 或 S4 等),所以调用 names(formals(f)) 可能会给我错误的列表的论点。当应用于 x 时,我需要调用类似 names(formals(f(x))) 的东西来获取 f 的参数。我举个小例子:

    # x is an integer vector, let f be the mean  
    > x <-1:10 
    > class(x)
    [1] "integer"

    # The mean has lots of methods, so I can't check the arguments of mean(x)
    > names(formals(mean))
    [1] "x"   "..."

    > getFunction("mean")
    function (x, ...) 
    UseMethod("mean")
    <bytecode: 0x0000000017535928>
    <environment: namespace:base>

    # This also gives an error, because mean.integer does not exist 
    > names(formals(getS3method("mean",class(x))))
    Error in getS3method("mean", class(x)) : 
      S3 method 'mean.integer' not found

    # Through researching I found out that the mean method actually 
    # applied to x is mean.default, so what I am actually looking for is:
    > names(formals(mean.default))
    [1] "x"     "trim"  "na.rm" "..."  

    # Aha, there is the 'na.rm' argument I was looking for, but the question remains: 
    # How can I find the arguments of some function f applied to some object x?

标签: rfunctionmethodsfunctional-programmingarguments

解决方案


推荐阅读