[R] change the value of vector based on the string of its name

David Winsemius dwinsemius at comcast.net
Fri Mar 24 23:45:14 CET 2017


> On Mar 24, 2017, at 10:12 AM, Qill Bel <qillbel at gmail.com> wrote:
> 
> Dear R-users,
> 
> Imagine I have 3 vectors:
> *proc1<-0*
> *proc2<-0*
> *cpd<-c("proc1","proc2")*

The `cpd` vector has only character values in it, and has no relation to either the `proc1` or `proc2` vectors. If you want it refer to  them (or contain their values),  then omit the quotes. The values will not retain their names in this instance. The R names `proc`` and `proc2` will be looked up and their values places in an unnamed numeric vector. You could however make it so with:

cpd<-c("proc1"=proc1,"proc2"=proc2)

#The quotes are not needed and so this would be equivalent"

cpd<-c( proc1=proc1, proc2=proc2)

There is a `get`-function, but teaching you how to use it to solve the problem is likely to be a disservice since it would allow you to continue using R as a macro-processor.

> 

> How can I change the value of proc1 to 1, based on vector cpd only?
> I tried with *as.factor(cpd[1])<-1*, but it produces an error.

Doesn't make much sense to me to use assignment to a factor in this instance, but that's probably because we come from different programming backgrounds. Neither your code nor mine would have produced a factor vector. You should say in natural language what it is that you want to happen.

(Perhaps) Try this:

cpd[1] <- 1

Or:

cpd['proc1'] <- 1


> 
> Any idea how could I achieve that?
> 
> 	[[alternative HTML version deleted]]

And learn to post in plain text. Reading the Posting Guide will also be a good idea. As would be studying a bit longer the "Introduction to R" that is shipped with every installation.


> 
> ______________________________________________
> R-help at r-project.org mailing list -- To UNSUBSCRIBE and more, see
> 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.

David Winsemius
Alameda, CA, USA



More information about the R-help mailing list