Reputation: 3168
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!
Upvotes: 2
Views: 2555
Reputation: 263451
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.
Upvotes: 6
Reputation: 66902
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.
Upvotes: 9
Reputation: 69221
I'm not sure I fully grasped the wikipedia article, but does indexing with [
achieve your desired result? A trivial example:
> dat <- data.frame(foo = rnorm(10), bar = rnorm(10))
> myVar <- "bar"
> dat[ , myVar]
[1] 1.354046574 0.551537607 0.779769817 0.546176894 -0.194116973 0.959749309
[7] -1.560839187 -0.024423406 -2.487539955 -0.201201268
or
> dat[ , myVar, drop = FALSE]
bar
1 1.354046574
2 0.551537607
3 0.779769817
....
Upvotes: 1