[R] Assigning value to a vector from within a function
David Winsemius
dwinsemius at comcast.net
Wed Oct 6 20:46:39 CEST 2010
On Oct 6, 2010, at 1:31 PM, Andrew Barr wrote:
> Hi all,
>
> I am having trouble assigning a value within a vector using a variable
> defined within a function. I suspect this has something to do with
> namespaces but I cannot figure it out. Please reply directly to me
> if you
> can help.
>
> ###begin code
> #simple vector
> test<-c(4,5,6)
>
> #simple function to get a value from a vector
> #works just like I would expect, has no problem indexing using the
> local
> function variable name "index"
>
> getvalue<-function(index){
> print(test[index])
> }
> getvalue(2)
But, but , but that just the "[" function.
> test<-c(4,5,6)
> `[`(test, 2)
[1] 5
> #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
More "buts", ... that's just the "[<-" function with a constant 20 or
perhaps it's an unsuccessful effort to make one.
> test[2] <- 20 # which gets parsed to something like `[<-`(test,
2, 20)
> `[<-`(test, 2, 20)
[1] 4 20 6
> test
[1] 4 20 6
> ###
>
> I don't understand why the function has no problem accessing the
> value, but
> cannot accomplish the assignment.
Scoping. You made an assignment inside a function and then did not
return a full object that was assignable as "test". Look what happens
if you do an assignment of the returned value of your function
> newtest <- update(2)
>
> newtest
[1] 20
> I need to be able to update vectors using
> index values which I pass from within a function.
Pass the object to the function and return what you want. If you want
the original to be altered, then do it like:
test <- modfn(test) # which is slightly more general than `[<-`(test,
2, 20)
But do it with:
.
.
return(test) }
at the end of the operations, i.e., return the full object, not just
its second element.
>
> Thanks for your help.
>
> Andrew Barr
--
David Winsemius, MD
West Hartford, CT
More information about the R-help
mailing list