如何接受不带引号的文本/字符参数 [英] How to take in text/character argument without quotes

查看:122
本文介绍了如何接受不带引号的文本/字符参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果问题不清楚,很抱歉。请自由改变它。

Sorry if the question is unclear. Feel free to change it.

所以基本上我试图找到一种方式,使一个函数的文本/字符串参数不需要引号。

So basically I am trying to find a way so that text/character string arguments for a function don't require quotes.

foo  = function(x, y, data){
    n1 = length(data[,x])
    n2 = length(data[,y])
    cat(n1, n1)
 }

如果我使用以下代码

data(survey)
foo(Sex, Fold, survey)

我会收到一条错误消息。但如果我使用以下:

I will get an error message. But if I use the following:

foo("Sex", "Fold", survey)

foo(1, 5, survey)

这个函数会给我想要的。所以我想知道是否有任何方法来构造函数,我不需要使用引号围绕列名称。谢谢!

the function will give me what I want. So I wonder if there is any way to construct the function such that I won't need to use quotes around the column names. Thanks!

推荐答案

好吧,这将符合以下符号:

Well, this will work with the symbols:

foo  = function(x,y, data){
    n1 <- length(eval(substitute(x),data))
    n2 <- length(eval(substitute(y),data))
    cat(n1,n2)  
}

如果你想要使用引用的变量名和整数索引,你可以简单地检查 x y 开始时用一些简单的 if-else 分支。

If you wanted this to work with quoted variable names and integer indices as well, you could simply check x and y at the start with some simple if-else branching.

eval(substitute()) idiom可能是危险的使用。 (在某些情况下,您可能无法预期的工作方式,并且在工作不正常时您可能无法实现。)

But it comes with the standard warning that the eval(substitute()) idiom can be dangerous to use. (You may not always be able to anticipate how it won't work in some cases, and you may not realize when it isn't working.)

这篇关于如何接受不带引号的文本/字符参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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