R中的函数如何识别作为参数传递的代码(或变量名)?
例如,假设我有一个带有列people
的数据帧gender
。如果使用dplyr
的filter
函数,则可以像这样过滤记录:
filter(people, gender=="M")
使用2个参数people
和gender=="M"
调用该函数。我希望R首先评估2个表达式,然后将它们的值作为参数传递给函数调用。但是,在函数调用的上下文中,gender
是未定义的变量,gender=="M"
本身将导致“找不到对象”错误。
如何在R中评估此函数调用,以及为什么上面的语法有意义?
R函数将指定变量或参数,您可以通过执行?function
例如?dplyr::filter
来查看它们。以下示例显示R如何解释函数的输入...
exampleFunc <- function(x, y){
x - y
}
# r will default that the first variable is x, and the second is y,
# as this is the order they are specified within the function
exampleFunc(5, 3)
# this is equivalent to
exampleFunc(x = 5, y = 3)
# but the variables within a function can be provided in any order if we specify what each variable is...
exampleFunc(y = 3, x = 5)
# while this takes x to be three and y to be five
exampleFunc(3, 5)