开发者

How can I eliminate quote marks around parameters in R function?

开发者 https://www.devze.com 2023-02-10 13:30 出处:网络
Here are the first few lines of an R function that works: teetor <- function(x,y) { require(\"quantmod\")

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 ab开发者_运维问答le to simply type:

teetor(GLD, GDX)


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号