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?
Let's see what happens in ?'s code using the {flow} package, it helps you inspect the logical path your code takes (follow the full lines):
flow::flow_run(?function(){}, out = "png")

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 = "png")
?function(){}

There we see that when the input is 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]

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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With