如何消除 R 函数中参数周围的引号?

发布于 2024-10-17 11:44:28 字数 459 浏览 2 评论 0原文

以下是有效的 R 函数的前几行:

teetor <- function(x,y) {

require("quantmod")
require("tseries")

alpha <- getSymbols(x, auto.assign=FALSE)
bravo <- getSymbols(y, auto.assign=FALSE)

t     <- as.data.frame(merge(alpha, bravo))

# ... <boring unit root econometric code>

}

当我传递两个股票代码作为函数参数时,我需要将它们用引号引起来:

teetor("GLD", "GDX")

我希望能够简单地键入:

teetor(GLD, GDX)

Here are the first few lines of an R function that works:

teetor <- function(x,y) {

require("quantmod")
require("tseries")

alpha <- getSymbols(x, auto.assign=FALSE)
bravo <- getSymbols(y, auto.assign=FALSE)

t     <- as.data.frame(merge(alpha, bravo))

# ... <boring unit root econometric code>

}

When I pass two stock symbols as function parameters, I need to enclose them with quotes:

teetor("GLD", "GDX")

I want to be able to simply type:

teetor(GLD, GDX)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

你げ笑在眉眼 2024-10-24 11:44:28

不。为了节省几次击键而牺牲清晰、简单的代码是一个坏主意。您创建的函数只能交互使用,不能从其他函数调用。

Don't. It's a bad idea to sacrifice clear, simple code just to save a couple of keystrokes. You have created a function that can only be use interactively, not called from another function.

很酷不放纵 2024-10-24 11:44:28

有几种方法可以做到这一点,但通常我不建议这样做。

通常,调用不带引号的内容意味着该对象本身位于搜索路径中。在不分配它的情况下执行此操作的一种方法是使用 with() 函数。

您可以通过 deparse(substitute(...)) 获取某个东西的名称,而无需它实际存在:

> blah <- function(a) {
    deparse(substitute(a))
  }
> blah(foo) 
[1] "foo"
> foo 
Error: object 'foo' not found

因此原则上您可以使用 deparse(substitute(...) 获取名称) 如上例所示,在您的 teetor 函数中,而不是传入名称。

There are several ways of doing this, but generally I wouldn't advise it.

Typically calling something without quotes like that means that the object itself is in the search path. One way to do this without assigning it is to use the with() function.

You can get the name of something without having it actually exist by deparse(substitute(...)):

> blah <- function(a) {
    deparse(substitute(a))
  }
> blah(foo) 
[1] "foo"
> foo 
Error: object 'foo' not found

So in principle you can get the names using deparse(substitute(...)) as in the above example in your teetor function instead of passing in the names.

掀纱窥君容 2024-10-24 11:44:28

好吧,我想一个解决方案是:

GLD <- "GLD"
GDX <- "GDX"
teetor(GLD,GDX)     # No need to quote GLD and GDX

再想一想,没关系。

Well, I suppose one solution is:

GLD <- "GLD"
GDX <- "GDX"
teetor(GLD,GDX)     # No need to quote GLD and GDX

On second thought, never mind.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文