[R] A More efficient method?

S Ellison S.Ellison at lgc.co.uk
Wed Jul 4 17:57:35 CEST 2007


#Given
Cat=c('a','a','a','b','b','b','a','a','b')	# Categorical variable

#and defining 
coding<-array(c(-1,1), dimnames=list(unique(Cat) ))

#(ie an array of values corresponding to your character array levels, and with names set to those levels)

coding[Cat]

#does what you want.

>>> Keith Alan Chamberlain <Keith.Chamberlain at Colorado.EDU> 04/07/2007 14:44:44 >>>
Dear Rhelpers,

Is there a faster way than below to set a vector based on values from
another vector? I'd like to call a pre-existing function for this, but one
which can also handle an arbitrarily large number of categories. Any ideas?

Cat=c('a','a','a','b','b','b','a','a','b')	# Categorical variable
C1=vector(length=length(Cat))	# New vector for numeric values

# Cycle through each column and set C1 to corresponding value of Cat.
for(i in 1:length(C1)){
	if(Cat[i]=='a') C1[i]=-1 else C1[i]=1
}

C1
[1] -1 -1 -1  1  1  1 -1 -1  1
Cat
[1] "a" "a" "a" "b" "b" "b" "a" "a" "b"

Sincerely,
KeithC.
Psych Undergrad, CU Boulder (US)
RE McNair Scholar

______________________________________________
R-help at stat.math.ethz.ch 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.

*******************************************************************
This email and any attachments are confidential. Any use, co...{{dropped}}



More information about the R-help mailing list