【问题标题】:Use a string as a condition in If- else在 If-else 中使用字符串作为条件
【发布时间】:2015-09-23 14:26:51
【问题描述】:

我有一个变量是 count_process = "time>=20" 现在我想在 IF 条件下使用它,例如

if(time>=20){ do something }

我该怎么做?

【问题讨论】:

  • 请发布一个可重现的示例。也许你需要eval(parse(text=count_process))
  • 如果我理解你的话if(count_process =="time>=20"){ do something }
  • 这感觉像是代码注入的地方。强烈不推荐。

标签: r variables if-statement conditional-statements


【解决方案1】:

一种选择是使用sub 提取数字子字符串并在if 条件中使用它

 val <- as.numeric(sub('[^0-9]+', '', count_process))
 if(time >= val){do something}

其他选项是使用eval(parse((虽然不推荐)

 if(eval(parse(text=count_process))){do something}

【讨论】:

  • 责备eval(parse(的任何理由/来源?
  • @MichaelChirico 可能是这个link,里面的链接很有帮助
猜你喜欢
  • 2021-01-13
  • 2019-05-06
  • 2013-04-29
  • 2018-04-12
  • 1970-01-01
  • 2021-12-29
  • 1970-01-01
  • 2022-11-03
  • 1970-01-01
相关资源
最近更新 更多