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

人盡茶涼 提交于 2019-12-09 13:32:57

问题


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)

回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/5011348/how-can-i-eliminate-quote-marks-around-parameters-in-r-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!