How to evaluate an expression with variables in R?

血红的双手。 提交于 2019-12-11 10:59:06

问题


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.

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

What's wrong with the code?


回答1:


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



回答2:


See: ?parse. Your demo code:

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

Update: based on @Anton's comment about the original goal - what about:

> f <- function(type, ...) {
+     assign('plt', do.call(deparse(substitute(type)), list(...)), envir = .GlobalEnv)
+ }
> f(mean, x = 1:20)
> plt
[1] 10.5

PS: I still trying to implement what the OP is after, not what he might or should be after -- that's why I used above assign and .GlobalEnv, although it's not a great idea BTW.



来源:https://stackoverflow.com/questions/20581757/how-to-evaluate-an-expression-with-variables-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!