如何用R中的变量求值表达式? [英] How to evaluate an expression with variables in R?

查看:73
本文介绍了如何用R中的变量求值表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望此代码将plt设置为10:

I expect this code to set plt equal to 10:

> var = "plt"
> eval(paste0(var, "<-", 10))
[1] "plt<-10"

但是,它返回一个字符串.

But instead, it returns a string.

我尝试了eval(as.expression(paste0(var, "<-", 10)))和其他选项,但仍然没有得到预期的结果.

I tried eval(as.expression(paste0(var, "<-", 10))) and other options, but it still doesn't give the expected result.

代码有什么问题?

推荐答案

如果我正确理解您的评论,则没有理由潜入eval(parse())的鲨鱼出没的水域.尝试这样的事情:

If I understand your comment correctly there is no reason to dive into the shark-infested waters of eval(parse()). Try something like this instead:

myfun <- function(x, fun) {
  if (is.character(fun)) fun <- match.fun(fun)
  fun(x)
}

myfun(1:5, mean)
#[1] 3
myfun(1:5, "mean")
#[1] 3

这篇关于如何用R中的变量求值表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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