Home > Mobile >  Advanced: Why ?function(){} works in R
Advanced: Why ?function(){} works in R

Time:05-04

I understand some operators and functions in R need to be backquoted before using the help function. However, I don't understand why ?function(){} also works. Does anyone have any idea on it?

CodePudding user response:

Let's see what happens in ?'s code using the {flow} package, it helps you inspect the logical path your code takes:

flow::flow_run(?function(){}, out = "1.png")

enter image description here

We see that when the expression is a call we call utils:::.helpForCall

Let's see what happens there, we cannot call flow::flow_run directly so we call flow::flow_debugonce to set up utils:::.helpForCall and call ? again

flow::flow_debugonce(utils:::.helpForCall, out = "2.png")
?function(){}

enter image description here

There we see that when the input in a call we call utils:::.tryHelp on the name of the function as a string. function(){} is a call to function and utils:::.tryHelp("function") opens the help file.


Bonus

@rawr wonders why ?cars[1] doesn't work, I haven't looked much into it but at a glance we see where the code takes a different path in .helpForCall:

flow::flow_debugonce(utils:::.helpForCall, out = "png")
?mtcars[1]

enter image description here

CodePudding user response:

If you try

debugonce(`?`)
?function(){}

you will arrive at this line

if (is.call(topicExpr)) 
  return(.helpForCall(topicExpr, parent.frame()))

So calling

debugonce(.helpForCall)

again will get to this line in .helpForCall

f <- expr[[1L]]

If you examine expr, it is a ?call with the following elements

expr
# function() {
# }

as.list(expr)
# [[1]]
# `function`
# 
# [[2]]
# NULL
# 
# [[3]]
# {
# }
# 
# [[4]]
# function(){}

and

class(expr[[1]])
# [1] "name"

Now, if you would ask me why

?mtcars[1]
# Error in .helpForCall(topicExpr, parent.frame()) : 

?mtcars[[1]] ## works

?asdflasdflansldfnalsdf[1]
# Error in eval(argExpr, envir) : object 'asdflasdflansldfnalsdf' not found

?asdflasdflansldfnalsdf[[1]] ## works

I have no idea

  • Related