R:评估一个字符串 [英] R: evaluate a string

查看:87
本文介绍了R:评估一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

事实证明,有必要定义一个函数eval_string,该函数将字符串当作表达式(/call)来求值.例如,如果:

It has proved necessary to define a function eval_string which evaluates a string as if it were an expression(/call). For example, if:

string <- 'cyl == 6 & disp > 200'

我想要:

eval_string(string, mtcars) 

等同于:

eval(quote(cyl == 6 & disp > 200), mtcars)

这是我的尝试:

eval_string <- function(string, ...) eval(parse(text = string), ...)

这似乎行得通,但是,我知道parse对此并不满意,并且对这种类型的编程没有太多的经验(无论是什么?).所以我的问题是:是否有更规范的方法来实现我想要的?为了在问题后面加上一些上下文,将eval_stringshiny结合使用;尤其是textInput函数.

which seems to work, however, I am aware parse is frowned upon, and do not have much experience with this type of programming (whatever it is?). So my question is: is there a more canonical way of achieving what I want? To put some context behind the question, eval_string will be used in conjunction with shiny; in particular, the textInput function.

为任何帮助喝彩.

感谢您的评论.当我使用textInput子集数据帧时,在Hadley指南的帮助下,我也想出了以下解决方案:

thanks for the comments guys. As I am using the textInput to subset a data frame, with help from Hadley's guide, I have come up with this solution also:

library(pryr)

subset_with_string <- function(string, data) {
  expr <- parse(text = string)[[1]]
  subset_calls <- c("==", "!=", "&", "|", ">", "<", ">=", "<=", "(")
  legal_call <- all(fun_calls(expr) %in% subset_calls)                          
  if (legal_call) {
    data[eval(expr, data), ]
  } 
  else {
    stop('string does not induce a legal subset call to evaluate!')
  }
}

subset_with_string("(cyl == 6 & hp > 100) | gear == 4", mtcars)

subset_with_string("rm('importantFile.doc')", mtcars)

推荐答案

为避免使用eval,我在Shiny应用程序中添加了以下内容:

To avoid using eval I have the following in a Shiny app:

dat<-try(do.call(subset,list(data,parse(text = string))),silent = TRUE)

dat <- try(do.call(subset, list(data,parse(text = string))), silent = TRUE)

if(!is(dat,'try-error'))return(dat)

if(!is(dat, 'try-error')) return(dat)

这篇关于R:评估一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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