Message-ID: <4DD6F8B8782D584FABF50BF3A32B03D801A2BBB4@MSGBOSCLF2WIN.DMN1.FMR.COM>
Date: 2005-04-29T20:23:18Z
From: Brahm, David
Subject: assign to an element of a vector
Fernando Saldanha [fsaldan1 at gmail.com] wrote:
> I am trying to find a way to assign values to elements of a vector
> that will be defined by a user.
> > a <- c(1,2,3)
> > get('a')[1] <- 0
> Error: Target of assignment expands to non-language object
Try this function:
g.assign <- function(i, pos=1, ..., value) {
x <- if (pos > 0) get(i, pos) else get(i, , parent.frame())
x[...] <- value
if (pos > 0) assign(i, x, pos) else assign(i, x, , parent.frame())
}
Your example becomes:
R> a <- c(1,2,3)
R> g.assign("a", pos=1, 1, value=0)
Note you use a positive <pos> (usually pos=1) for "global" variables,
and
pos=0 for "local" variables inside a function. The <...> construction
allows
this function to work for arrays too, but the downside is that you must
type
"value=" explicitly.
-- David Brahm (brahm at alum.mit.edu)