0

I wanted to find which function in base R has the greatest number of arguments.

> objs <- mget(ls("package:base"), inherits = TRUE)
> funs <- Filter(is.function, objs)

one easy way was to use sapply as follows

f_arg_length <- sapply(funs, function(x) length(formals(x)))
f_arg_length[which.max(f_arg_length)]

but I also tried an explicit loop to do the same and my code was

max_fun_name <- ""
max_fun <- 0
for(x in 1:length(funs)) {
  if (length(formals(names(funs[x]))) > max_fun) 
{
  max_fun <-  length(formals(names(funs[x])))
  max_fun_name <- names(funs[x])
}
}
max_fun_name
max_fun

I am unable to understand why elements of funs are passed in formals() with names() when referencing with index (as seen in the explicit loop), while the same can be achieved without names() when referencing without index (as seen in the case of sapply). Can someone please explain the reason why these two ways of referencing the same thing produce noticeable differences?

  • I'm unclear exactly what you are asking here. The `names()` are only coming from the named list created by `mget()` and doesn't really have much to do with the functions themselves. Maybe the confusion is from indexing with `funs[x]` rather than `funcs[[x]]`. Maybe checkout the [difference between \[\] and \[\[\]\] in R](https://stackoverflow.com/questions/1169456/the-difference-between-and-notations-for-accessing-the-elements-of-a-lis) – MrFlick May 15 '18 at 20:16
  • I'm asking why there is this noticeable difference when I'm referencing the same thing in two different ways? Yes, indexing with [[]] instead of [] does help because I no longer need to provide names() when I use [[]]. Thus, making this similar to the sapply call. – Narin Dhatwalia May 15 '18 at 20:48
  • But you're not referencing the same things two different ways. (I'm not even sure exactly which two things you think are the same.) But `sapply()` iterates over the values in a list, while `[]` on a named list returns a sub-list and does not extract the values in the same way. – MrFlick May 15 '18 at 20:51
  • the same thing being the values in the list. The two different ways of referencing them being sapply() and []. Could you shed some more light on how [] works differently on a named list? I assumed that the thing being referenced was the same, so this would help clear things out. – Narin Dhatwalia May 15 '18 at 20:57
  • The link I provided originally explains the difference between `[ ]` and `[[ ]]` (see all the answers, not necessarily the accepted one). But basically `[` subsets a list while `[[` extracts elements from a list. – MrFlick May 15 '18 at 20:59

0 Answers0