Morgan Ball
Morgan Ball

Reputation: 790

Modify function in global environment

Not sure if this is possible but worth an ask. I need to be able to modify a function that is loaded into the global environment. For example, lets say I had a function like the below that returned the median of a vector

myVec<-c(1,2,3,4,5,5,5,6,7,8,9,10)

average<-function(x){
  median(x)
}

average(myVec)

Now I wanted to update the function to return the mean but without changing the overall structure of the function so I want to update average() so it becomes

average<-function(x){
  mean(x)
}

Is this possible? I'm guessing some form of writing the function to a temp file and calling readLines() and writeLines() but as of yet I've not had any success.

Upvotes: 0

Views: 204

Answers (1)

r.user.05apr
r.user.05apr

Reputation: 5456

I believe you mean a closure:

myVec<-c(1,2,3,4,5,5,5,6,7,8,9,10)

# this will create your function
create.average <- function (fun) {
  my.average <- function (x) {
    fun(x)
  }
  return(my.average)
}
# define average as mean
average <- create.average(mean)
average(myVec)
mean(myVec) # only to verify result

# re-define average as median
average <- create.average(median)
average(myVec)
median(myVec) # only to verify result

Upvotes: 1

Related Questions