Skip to content

assign a value to an element

4 messages · Marc Girondot, William Dunlap, David Winsemius +1 more

#
Do not use assign().  It is a relic from the 1980s.

Instead, decide where you want your
variables to live, perhaps in a list,
   where<-list()
or perhaps in an environment,
   where<-new.env()
or
  where<-environment().
Then use where[[varName]] to refer to the variable.  You can
use further subsetting functions on that.  E.g.,
   where <- environment() # the current environment
   varName <- "qwerty"
   where[[varName]] <- 1:10
   where[[varName]][2:3] <- log(where[[varName]][9:10])
   where[[varName]] 
   # [1]  1.000000  2.197225  2.302585  4.000000
   # [5]  5.000000  6.000000  7.000000  8.000000
   # [9]  9.000000 10.000000

Bill Dunlap
Spotfire, TIBCO Software
wdunlap tibco.com
#
On Mar 18, 2012, at 2:24 PM, Marc Girondot wrote:

            
Yes and further, vec[4] in your example does not have a name, since  
you created vect as an unnamed vector. It's not generally optimal  
practice to build up strings and pass them to eval(parse()).

However there is some assignment possible by name to data.frame rows  
with "["

 > vecdf <- data.frame(vec=vec)
 > vecdf['a' , ] <- 20
 > vecdf
   vec
a  20
b  10
c   3
d   4
e   5
f   6
g   7
h   8
i   9
j  10

Where the rowname value is used as the index for assignment. Is that  
sufficiently elegant?
David Winsemius, MD
West Hartford, CT
#
I am not sure that I understand but does something like this do what you want?

ec<-1:10
vec[vec==4] <- 100

vec <- 1:10
vec[ vec==4 | vec==8] <- 100

vec <- 1:10
aa <- 50
vec[vec==4] <- aa


John Kane
Kingston ON Canada
____________________________________________________________
FREE 3D MARINE AQUARIUM SCREENSAVER - Watch dolphins, sharks & orcas on your desktop!