0

I am facing an apparently easy problem in R. That is to make a function (say "foo") to quote (i.e., make a string) from a line of "code". This is the example:

 foo( SELECT * FROM DATA LIMIT 100 )

The result must be:

"SELECT * FROM DATA LIMIT 100" 

which is quoted (it is a string), without evaluation. That must work for any thing, like:

foo( 1234 ERE 34e3 & ) 

has to give:

"1234 ERE 34e3 &"

foo( x = 33 + 34 ) 

has to give:

"x = 33 + 34"

I am sure i miss something, but i really can not find a solution to this simple problem.

NEW EDIT :

We had many comments about the question and possible answers, very useful (see below), but none got the proper answer.

To clarify, i am ONLY interested on a general solution to the question I make. So I look to know if there is a function that can do what i say above, i.e. : quote ANY code/text,
INDEPENDENTLY of the specific context for what the function will be used.

Seems the answer is not easy or that is impossible. We can still try to see if we get a clever idea. Thank you !

4

3 回答 3

3

如果您foo( 1234 ERE 34e3 & )在 R 命令行中键入,则在调用1234 ERE 34e3 &之前进行评估。foo这意味着无论你如何定义foo,传入不是有效的 R 代码的东西总是会引发错误。

您需要将调用包装起来footry处理tryCatch此问题。

正如托马斯在评论中指出的那样,1234 ERE 34e3 &甚至不会正确解析,更不用说评估,所以try没用。

我建议你放弃这个想法,做其他人都会做的事情:
如果你直接在命令行输入代码,那么只需""在它周围输入多余的字符。如果您的代码在文件中,请使用readLinesscan或其他)将代码作为字符串获取。

于 2013-08-01T09:37:36.850 回答
3

我会建议类似:

foo <- function(){
    readLines(n=1)
}
z <- foo()
SELECT * FROM DATA LIMIT 100
z
#[1] "SELECT * FROM DATA LIMIT 100"

但是,没有上下文就很难说。

于 2013-08-01T09:16:10.120 回答
2

我的几分钱,函数调用不能真正处理空格。所以我什至不确定你能不能做“SELECT * FROM DATA LIMIT 100”,因为之间有空格。否则这有效

foo <- function(...){
  cl <- match.call(expand.dots=FALSE)
  cl <- paste(cl)[2]
  cl <- substr(cl, 6, nchar(cl)-1)
  cl
 }
 foo(FROMDATALIMIT)
 foo(x = 5)
 foo(x = 5+5)
 foo(from&data)
 foo(x = 5, FROMDATALIMIT)
 foo(from data limit) #doesn't work
于 2013-08-01T09:34:02.583 回答