Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

metaprogramming - In R, how to turn character to verbatim expression?

If I do this:

parse(text="foo()")

I get:

expression(foo())

But what I really need is:

foo()

So basically "foo()" -> foo()

Also, if I try:

as.symbol("foo()")

I get:

`foo()`

I don't want the tick marks

question from:https://stackoverflow.com/questions/65640767/in-r-how-to-turn-character-to-verbatim-expression

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Something like this?

foo <- function(x) pi*x
eval(as.symbol("foo"))(1:10)
#[1]  3.141593  6.283185  9.424778 12.566371 15.707963 18.849556 21.991149
#[8] 25.132741 28.274334 31.415927

The return value of eval(.) can be assigned to an object and it will be a function.

f <- eval(as.symbol("foo"))
f
#function(x) pi*x

f(2)
#[1] 6.283185

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...