[R] `acting' on variables

Damon Wischik djw1005 at cam.ac.uk
Thu Jul 10 01:00:24 CEST 2003


> gompertz.estimates <- function(age, surv){
>   ...
>   app.age <- ageseq[1:length(l.est)]
>   list(app.age = app.age, l.est = round(l.est, digits=0))
>   }
> The components in the list are the things I
> would like to add to the columns in my incomplete
> life table.

The way I would do this is by adding to the function:
  gompertz.estimates <- function(age,surv) {
    ...
    list(age=c(age,app.age), surv=c(surv,l.est))
    }
and then invoke it by
  res <- gompertz.estimates(age,surv)
  age <- res$age
  surv <- res$surv

A dangerous way to do what I think you asked can be programmed along these
lines:
  f <- function(i) {
    nameOfParam <- deparse(substitute(i))
    j <- i*3
    assign(nameOfParam, j, inherits=TRUE)
    "I'm an evil function with side-effects"
    }
  val <- 3
  f(val)
  val
You'll see that val has been altered behind your back. One trouble with
this function is that it demands to be called with a straight variable. If
you do 
  f(val+3)
it won't work. I can't imagine any situation where this approach is
useful. I have on one occasion needed side-effects, and the <<- operator
was useful in that case. 

Damon.




More information about the R-help mailing list