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?