计算传递给函数的参数数量 [英] Count number of arguments passed to function

查看:48
本文介绍了计算传递给函数的参数数量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有兴趣计算传递给函数的参数数量. length 不能用于此目的:

I'm interested in counting a number of arguments passed to a function. length can't be used for that purpose:

>> length(2,2,2,2,2)
Error in length(2, 2, 2, 2, 2) : 
  5 arguments passed to 'length' which requires 1

这很明显,因为 length 接受1个参数,所以:

This is obvious as length takes 1 argument so:

length(c(2,2,2,2,2))

将产生预期的结果-5.

would produce the desired result - 5.

我想这样调用我的函数 myFunction(arg1,arg2,arg3).这可以通过使用省略号来实现:

I want to call my function like that myFunction(arg1, arg2, arg3). This can be done with use of an ellipsis:

myCount <- function(...) {length(list(...))}

myCount 将产生所需的结果:

>> myCount(2,2,2,2,2)
[1] 5

问题

这是非常低效的.我在大量参数上调用此函数,创建仅用于计数对象数量的列表是浪费的.返回传递给函数的参数数量的更好方法是什么?

Problem

This is awfully inefficient. I'm calling this function on substantial number of arguments and creating lists just to count number of objects is wasteful. What's the better way of returning the number of arguments passed to a function?

推荐答案

如何

myCount <- function(...) {length(match.call())-1}

这只是检查传递的调用(并为函数名称本身删除1)

This just inspects the passed call (and removes 1 for the function name itself)

这篇关于计算传递给函数的参数数量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆