Does R have reflection?
http://en.wikipedia.org/wiki/Reflection_(computer_programming)
basically what i want to do is this:
currentRun = "run287"
dataFrame$currentRun= someVar;
such that dataFrame$currentRun is equivalent to dataFrame$run287.
This hasn't prevented me from solving any problems, but from an academic standpoint I would like to know if R supports reflective programming. If so, how would one go about using reflection in the example given?
Thank you!
yes, R supports reflective programming.
here is an R version of the example:
foo <- function()1
# without reflection
foo()
# with reflection
get("foo")()
probably such as get, assign, eval is relevant. see online helps of them.
The use of the "$" operator should be discouraged in programming because it does not evaluate its argument, unlike the more general "[["
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
Which will succeed if the properties (in particular length) of myVar are correct. It would not be correct to say the datFrame$currentRun is equivalent to dataFrame$run287, but is is correct that character variables can be interpreted as column names. There is also a eval(parse(text="...")) construct, but it is better to avoid if possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With