1

Suppose I have four doubles a, b, c, d that at various points in my script will assume different real numbers. Assume also that all four doubles have values that center around another double called X. Namely, the following relationships must always hold:

  • a = X + 1
  • b = X + 5
  • c = X + 10
  • d = X + 15

In my script, the value of X is always changing. How do I write a function such that a, b, c, d change alongside X?

Creating the setAll function below and calling whenever X changes will of course not work but is in the spirit of what I want.:

setAll <- function(X) {
    a = X + 1
    b = X + 5
    c = X + 10
    d = X + 15
}
setAll(100) #if X = 100
2
  • What about using a custom environment for such variables instead of hacking in the .GlobalEnv? Or your could also follow some OO guidelines especially with reference classes: adv-r.had.co.nz/R5.html Commented Oct 13, 2013 at 13:27
  • @daroczig You are welcome to post an answer with an example of either solutions, which indeed sound like superior solutions. Commented Oct 13, 2013 at 13:42

2 Answers 2

5

If you'd want to keep the clutter at a minimal level in the .GlovalEnv, it might be better to keep all these variables in a separate environment, e.g.:

> setAll <- function(X) {
+     if (!(exists('myParams') && is.environment(myParams))) {
+         myParams <- new.env()
+     }
+     myParams$a = X + 1
+     myParams$b = X + 5
+     myParams$c = X + 10
+     myParams$d = X + 15
+ }
> setAll(100) #if X = 100
> myParams$a
[1] 101

Or you might just create a reference class in the means of OO programming as an alternative solution:

> myParam <- setRefClass('myParam', fields = list('X' = 'numeric', 'a' = 'numeric', 'b' = 'numeric', 'c' = 'numeric', 'd' = 'numeric'))
> myParam$methods(initialize = function(X, ...) {
+     .self$a <- X + 1
+     .self$b <- X + 5
+     .self$c <- X + 10
+     .self$d <- X + 15
+     callSuper(...)
+ })
> foo <- myParam(pi)
> foo$a
[1] 4.141593
> foo$b
[1] 8.141593
...

Sure, these are just initial and dummy wire-frames, but hopefully this would be useful for further ideas.

Sign up to request clarification or add additional context in comments.

Comments

1

If you are working with scripts and you want these global variables in your workspace then use the <<- operator: ?"<<-" Be careful though - this approach assumes that your critical variables don't get changed by any means other than what you intend, and are not very portable.

Update: Your setAll function should work if you change it to setAll <- function() - no argument is needed if X is reset each time with the <<- operator.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.