字符串作为函数参数r [英] character string as function argument r

查看:620
本文介绍了字符串作为函数参数r的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用dplyr并创建代码来计算使用ggplot绘制的新数据。

I'm working with dplyr and created code to compute new data that is plotted with ggplot.

我想使用此代码创建一个函数。它应该接受由dplyr处理的数据帧的列的名称。但是,尝试使用列名不起作用。请考虑以下最小示例:

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. 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?

推荐答案

如果你想创建一个接受字符串B作为参数的函数(如在你的问题的标题中)

If you want to create a function which accepts the string "B" as an argument (as in you question's title)

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

如果要创建一个接受捕获B作为参数的函数(如dplyr中)

If you want to create a function which accepts captures B as an argument (as in 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)

您可以在高级R 中找到更多信息

You can find more information in Advanced R

dplyr 0.3。具有后缀_的函数接受字符串或表达式作为参数

dplyr makes things easier in version 0.3. 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)

在此小插曲

这篇关于字符串作为函数参数r的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆