将变量名传递给R中的函数 [英] Passing a variable name to a function in R

查看:61
本文介绍了将变量名传递给R中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到,有很多软件包允许您传递符号名称,这些名称在调用函数的上下文中甚至可能无效.我想知道这是如何工作的,以及如何在自己的代码中使用它?

I've noticed that quite a few packages allow you to pass symbol names that may not even be valid in the context where the function is called. I'm wondering how this works and how I can use it in my own code?

以下是ggplot2的示例:

Here is an example with ggplot2:

a <- data.frame(x=1:10,y=1:10)
library(ggplot2)
qplot(data=a,x=x,y=y)

xy在我的命名空间中不存在,但是ggplot理解它们是数据帧的一部分,并将其评估推迟到有效的上下文中.我尝试做同样的事情:

x and y don't exist in my namespace, but ggplot understands that they are part of the data frame and postpones their evaluation to a context in which they are valid. I've tried doing the same thing:

b <- function(data,name) { within(data,print(name)) }
b(a,x)

但是,这不幸地失败了:

However, this fails miserably:

Error in print(name) : object 'x' not found

我做错了什么?如何运作?

What am I doing wrong? How does this work?

注意:不是不是推荐答案

我最近发现了我认为是传递变量名称的更好方法.

I've recently discovered what I think is a better approach to passing variable names.

a <- data.frame(x = 1:10, y = 1:10)

b <- function(df, name){
    eval(substitute(name), df)
}

b(a, x)
  [1]  1  2  3  4  5  6  7  8  9 10

更新:该方法使用非标准评估.我开始解释,但很快就意识到哈德利·威克汉姆(Hadley Wickham)做得比我更好.阅读此 http://adv-r.had.co. nz/Computing-on-the-language.html

Update The approach uses non standard evaluation. I began explaining but quickly realized that Hadley Wickham does it much better than I could. Read this http://adv-r.had.co.nz/Computing-on-the-language.html

这篇关于将变量名传递给R中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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