R函数如何获取作为参数传递的确切代码?

问题描述 投票:0回答:1

R中的函数如何识别作为参数传递的代码(或变量名)?

例如,假设我有一个带有列people的数据帧gender。如果使用dplyrfilter函数,则可以像这样过滤记录:

filter(people, gender=="M")

使用2个参数peoplegender=="M"调用该函数。我希望R首先评估2个表达式,然后将它们的值作为参数传递给函数调用。但是,在函数调用的上下文中,gender是未定义的变量,gender=="M"本身将导致“找不到对象”错误。

如何在R中评估此函数调用,以及为什么上面的语法有意义?

r function filter syntax
1个回答
0
投票

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)
© www.soinside.com 2019 - 2024. All rights reserved.