简体   繁体   English

字符串作为函数参数r

[英]character string as function argument r

I'm working with dplyr and created code to compute new data that is plotted with ggplot. 我正在使用dplyr并创建了代码来计算用ggplot绘制的新数据。

I want to create a function with this code. 我想用此代码创建一个函数。 It should take a name of a column of the data frame that is manipulated by dplyr. 它应该使用由dplyr操作的数据框的列的名称。 However, trying to work with columnnames does not work. 但是,尝试使用列名不起作用。 Please consider the minimal example below: 请考虑以下最小示例:

df <- data.frame(A = seq(-5, 5, 1), B = seq(0,10,1))

library(dplyr)
foo <- function (x) {
         df %>%
            filter(x < 1)
}

foo(B)

Error in filter_impl(.data, dots(...), environment()) : 
  object 'B' not found 

Is there any solution to use the name of a column as a function argument? 有什么解决方案可以将列名用作函数参数?

If you want to create a function which accepts the string "B" as an argument (as in you question's title) 如果要创建一个接受字符串“ B”作为参数的函数(如问题标题所示)

foo_string <- function (x) {
         eval(substitute(df %>% filter(xx < 1),list(xx=as.name(x))))
}
foo_string("B")

If you want to create a function which accepts captures B as an argument (as in dplyr) 如果要创建一个将捕获B作为参数的函数(如dplyr)

foo_nse <- function (x) {
         # capture the argument without evaluating it
         x <- substitute(x)
         eval(substitute(df %>% filter(xx < 1),list(xx=x)))
}
foo_nse(B)

You can find more information in Advanced R 您可以在Advanced R中找到更多信息。

Edit 编辑

dplyr makes things easier in version 0.3. dplyr在0.3版dplyr事情变得更容易。 Functions with suffixes "_" accept a string or an expression as an argument 带后缀“ _”的函数接受字符串或表达式作为参数

 foo_string <- function (x) {
             # construct the string
             string <- paste(x,"< 1")
             # use filter_ instead of filter
             df %>% filter_(string)
    }
foo_string("B")
 foo_nse <- function (x) {
             # capture the argument without evaluating it
             x <- substitute(x)
             # construct the expression
             expression <- lazyeval::interp(quote(xx < 1), xx = x)
             # use filter_ instead of filter
             df %>% filter_(expression)
    }
foo_nse(B)

You can find more information in this vignette 您可以在此小插图中找到更多信息

I remember a similar question which was answered by @Richard Scriven. 我记得@Richard Scriven回答了类似的问题。 I think you need to write something like this. 我认为您需要编写这样的内容。

foo <- function(x,...)filter(x,...) 

What @Richard Scriven mentioned was that you need to use ... here. @Richard Scriven提到的是,您需要在这里使用... If you type ?dplyr, you will be able to find this: filter(.data, ...) I think you replace .data with x or whatever. 如果键入?dplyr,将可以找到以下内容: filter(.data, ...)我认为您可以用x或其他替换.data。 If you want to pick up rows which have values smaller than 1 in B in your df, it will be like this. 如果要在df中拾取值小于B中1的行,则将像这样。

foo <- function (x,...) filter(x,...)
foo(df, B < 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM