I'm trying to get the arguments of a function, where the function name is stored as a string func_name. Normally I would do this as formals(func_name) and this works fine. However, I have a particular case where func_name has the package name attached as well, e.g. package::func_name.
The problem is that calling formals(package::func_name) I get:
Error in get(fun, mode = "function", envir = envir) :
object 'package::func_name' of mode 'function' was not found
This works if I remove the package:: bit, so the problem is clearly the presence of package::.
The reason I need to this is because the formals() command is inside a function inside an R package that I maintain, and I want to call this function from another package that I am building. Hence, I have to use the package::func_name syntax in the call.
Is there any way to somehow modify the formals() command to accept the package::func_name format? I guess I could also just remove the package:: part of the string but this seems a bit hacky. Any suggestions?
CodePudding user response:
You probably can't do it with the :: operator but you can specify the environment representing the name space of your package, e.g.:
formals('gls', envir=getNamespace('nlme'))
CodePudding user response:
Note that base::subset is R code that evaluates to the function so "base::subset" is not the name of the function; thus, evaluating it provides an easy solution (although the use of eval tends to be discouraged).
func_name <- "base::subset"
formals(eval(parse(text = func_name)))
An alternative is to pick it apart, get it and then use formals:
func_name |>
read.table(text = _, sep = ":") |>
with(get(V3, envir = asNamespace(V1), inherits = FALSE)) |>
formals()
