r - 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?
解决方案
推荐阅读
- html - Visual Studio 调试错误“错误处理启动:错误:无法附加到主目标
- python - Pandas Groupby、Sum 和 Flatten Dataframe
- roblox - 当玩家在与 NPC 互动时选择特定的对话选项时,我如何进行某些操作?
- msbuild - aspnet_regiis.exe 的“-site”选项有什么作用?
- kubernetes - tcpdump 到 kubernetes 负载均衡器分配的服务
- python - 将列表转换为字典,字符串作为键,浮点数作为值列表
- c++ - 如何使用线程更新纹理
- docker - 如何在不使用 docker 命令的情况下将 docker 镜像推送到 nexus3 存储库?
- reactjs - 在 React Router 中使用自定义路由器开关
- c++ - 一个无效参数被传递给一个认为无效参数致命的函数?