wes*_*erA 2 reflection computer-science r metaprogramming
R有反射吗?
http://en.wikipedia.org/wiki/Reflection_(computer_programming)
基本上我想做的是这样的:
currentRun = "run287"
dataFrame$currentRun= someVar;
Run Code Online (Sandbox Code Playgroud)
这dataFrame$currentRun相当于dataFrame$run287.
这并没有阻止我解决任何问题,但从学术角度来看,我想知道R是否支持反思编程.如果是这样,如何在给出的例子中使用反射?谢谢!
是的,R支持反射编程.
这是示例的R版本:
foo <- function()1
# without reflection
foo()
# with reflection
get("foo")()
Run Code Online (Sandbox Code Playgroud)
可能是get,等assign,eval是相关的.看到他们的在线帮助.
在编程时应该不鼓励使用"$"运算符,因为它不会评估它的参数,不像更普遍的"[["
currentRun = "run287"
dataFrame[[currentRun]]= someVar # and the";" is superflous
> dat <- data.frame(foo = rnorm(10), bar = rnorm(10))
> myVar <- "bar2"
> bar2 <- 1:10
> dat[[myVar]] <- bar2
> str(dat)
'data.frame': 10 obs. of 3 variables:
$ foo : num -1.43 1.7091 1.4351 -0.7104 -0.0651 ...
$ bar : num -0.641 -0.681 -2.033 0.501 -1.532 ...
$ bar2: int 1 2 3 4 5 6 7 8 9 10
Run Code Online (Sandbox Code Playgroud)
如果myVar的属性(特别是长度)正确,哪个会成功.说datFrame $ currentRun等同于dataFrame $ run287是不正确的,但是字符变量可以解释为列名是正确的.还有一个eval(parse(text ="..."))构造,但最好尽可能避免.