[R] Assigning value to a vector from within a function

Peter Langfelder peter.langfelder at gmail.com
Wed Oct 6 20:16:05 CEST 2010


>
> #another simple function to update the value in a vector
> update<-function(index){
> test[index]<- 20
> }
> update(2)
> test
> #The update() function silently fails to accomplish the update

Replace the '<-' by '<<-' and you'll be good to go if you call the
function from a global environment. More generally, look up
environments since you may want to update the variable in the
environment of the calling code which may not be the global
environment.

Remember that when you call a function, all arguments are copied, so
you do your operation on a copy that's discarded after the function
ends. The most transparent way to get what you want is to re-code the
function as

update<-function(test, index){
test[index]<- 20
test
}

and then write

test = update(test, index)

Peter



More information about the R-help mailing list