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 > -----Original Message----- > From: r-help-boun...@r-project.org [mailto:r-help-boun...@r-project.org] On > Behalf > Of Marc Girondot > Sent: Sunday, March 18, 2012 11:25 AM > To: r-help@r-project.org > Subject: [R] assign a value to an element > > Assign can be used to set a value to a variable that has name as a value of > another > variable. Example: > > > name<-"essai" > > assign(name, "plouf") > > essai > [1] "plouf" > > OK. > But how to do the same when it is only an element of a vector, data frame and > so on > that must be changed. > > > vec<-1:10 > > vec > [1] 1 2 3 4 5 6 7 8 9 10 > > vec[4] > [1] 4 > > name<-"vec[4]" > > assign(name, 100) > > vec > [1] 1 2 3 4 5 6 7 8 9 10 > > The reason is probably here (from help of assign): > assign does not dispatch assignment methods, so it cannot be used to set > elements of > vectors, names, attributes, etc. > > > I have found this solution: > > eval(parse(text=paste(name, "<-100", sep=""))) > > vec > [1] 1 2 3 100 5 6 7 8 9 10 > > Is-it the only way ? It is not very elegant ! > > Thanks a lot > > Marc > > __________________________________________________________ > Marc Girondot, Pr > > Laboratoire Ecologie, Systématique et Evolution > Equipe de Conservation des Populations et des Communautés > CNRS, AgroParisTech et Université Paris-Sud 11 , UMR 8079 > Bâtiment 362 > 91405 Orsay Cedex, France > > Tel: 33 1 (0)1.69.15.72.30 Fax: 33 1 (0)1.69.15.73.53 > e-mail: marc.giron...@u-psud.fr > Web: http://www.ese.u-psud.fr/epc/conservation/Marc.html > Skype: girondot > [[alternative HTML version deleted]] ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.