[R] Assigning value to a vector from within a function
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
> #simple function to get a value from a vector
> #works just like I would expect, has no problem indexing using the
> function variable name "index"
But, but , but that just the "[" function.
> `[`(test, 2)
> #another simple function to update the value in a vector
> test[index]<- 20
> #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 <- 20 # which gets parsed to something like `[<-`(test,
> `[<-`(test, 2, 20)
 4 20 6
 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)
> 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,
But do it with:
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