Count number of arguments passed to function

自古美人都是妖i 提交于 2020-05-12 03:27:27

问题


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

This is obvious as length takes 1 argument so:

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

would produce the desired result - 5.

Solution

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 would produce the desired result:

>> 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?


回答1:


How about

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

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



来源:https://stackoverflow.com/questions/44011918/count-number-of-arguments-passed-to-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!