如何“评估"? "paste0&"返回的结果? [英] How to "eval" results returned by "paste0"?

查看:79
本文介绍了如何“评估"? "paste0&"返回的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎我永远无法评估返回的'paste0'值以及所有带引号的字符.我是否必须使用'substr'或'gsub'删除这些引号?

It seem that I can never get the returned values of 'paste0' been evaluated , as well as any characters that have been quoted. Do I have to use 'substr' or 'gsub' to remove these quotation marks ?

eval(paste0('1','+','1')) 
[1] "1+1" 
eval(expression(paste0('1','+','1'))) 
[1] "1+1" 
eval(expression("1+1")) 
[1] "1+1" 
eval("1+1") 
[1] "1+1" 
eval(expression(1+1)) 
[1] 2 
eval(1+1) 
[1] 2

推荐答案

由字符串组成的表达式就是字符串,对字符串求值只会返回该字符串(如果在命令行中给R一个字符串,则只需再次看到字符串).这就是为什么您的尝试都没有奏效的原因(做得好,他们只是没有按照您的意愿去做).引号不是字符串的一部分,而是字符串的显示方式,因此gsub将无济于事.

An expression consisting of a string is just the string, evaluating the string just returns the string (if you give R a string at the command line then you will just see the string again). That is why none of your attempts worked (well the did work, they just did not do what you wanted). The quotes are not part of the string, just how it is displayed, so gsub will not help.

您需要将字符串解析为一个表达式,如注释所示,但要注意以下几点:

You need to parse the string into an expression, as the comment shows, but be aware of the following:

> library(fortunes)
> fortune(106)

If the answer is parse() you should usually rethink the question.
   -- Thomas Lumley
      R-help (February 2005)

> fortune(181)

Personally I have never regretted trying not to underestimate my own future
stupidity.
   -- Greg Snow (explaining why eval(parse(...)) is often suboptimal, answering
      a question triggered by the infamous fortune(106))
      R-help (January 2007)

人们使用paste0parseeval尝试执行的大多数操作可以使用其他工具更快,更简单地完成.构造一个字符串,进行解析和评估,就像在说您知道从波士顿到纽约的捷径,因此,每次您要从城市A到城市B时,都首先要从城市A到波士顿,请使用您的快捷方式,然后从纽约到B.如果您从罗德岛到新泽西,这可能很好,但在伦敦和巴黎之间往返的效率不高.解析构造的字符串也可能导致难以发现错误.

Most things that people try to do using paste0, parse, and eval can be done quicker and more simply using other tools. Construction a string, parsing, and evaluating it is kind of like saying that you know a shortcut from Boston to New York and therefore every time you want to go from city A to city B you first go from A to Boston, use your shortcut, then go from New York to B. This may be fine if your going from Rhode Island to New Jersey, but is not very efficient for going between London and Paris. Parsing constructed strings can also lead to difficult to find bugs.

您可能会考虑使用bquotesubstitute之类的功能:

You might consider using functions like bquote or substitute:

> eval( bquote( .(a) + .(b), list(a=1, b=2) ) )
[1] 3

或其他更直接的工具.如果您告诉我们您要做什么,那么我们也许可以提出更好的方法.

Or other more direct tools. If you tell us what you are trying to do then we may be able to suggest better approaches.

这篇关于如何“评估"? "paste0&"返回的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆