r - 如何在R中获取闭包的参数数量
问题描述
我在变量中有函数:
foo <- function(a, b) {}
我可以用:
body(foo)
对于函数的源代码,我可以使用这个:
length(substitute(function(a, b) {})[[2]])
但前提是我将函数内联。那么如何获取函数的参数数量呢?
我也试过
length(foo)
# 1
所以这不起作用。我想编写可以与可以具有 1 个或 2 个参数的处理程序一起使用的函数,所以我已经编写了通用实用程序:
#' Function call function fn with the only arguments it accept
invoke <- function(fn, ...) {
if (!is.function(fn)) {
stop("invoke: argument need to be a function")
}
count <- length(substitute(fn)[[2]])
do.call(fn, list(...)[1:count])
}
还是更好的方法?我有这样的功能:
fn1 <- function(a, b) {
}
fn2 <- function() {
}
我想调用他们两个,而不会对未使用的参数有错误
invoke(fn1, 10, 20)
invoke(fn2, 10, 20)
第二个应该忽略这两个论点。
解决方案
推荐阅读
- c# - Linq 查询仅对高于特定阈值的值求和
- outlook-web-addins - 如何使加载项固定到电子邮件项目?
- python - 将元组插入 SQlite 数据库
- powershell - 使用 powershell 的 WinMerge 命令行
- c# - 重置 unity AR 会话以在 iOS 上找到可追踪的飞机
- python - 将 curl 转换为 python:HTTP 415 不支持的媒体类型
- r - 摘要函数返回 Null 而不是 Max、Min 等
- html - 使画布伸展以填满窗口
- html - HTML 元素在 WordPress 中是不可见的
- java - 在 FlinkRunner 上使用 Beam 的 KafkaIO 时如何修复 NotSeraliazableException