[R] factor vector manipulation

Weiwei Shi helprhelp at gmail.com
Fri Jun 3 21:07:57 CEST 2005


Hi,
I have one question on factor vector.
I have 3 factor vectors:

a<-factor(c("1", "2", "3"))
b<-factor(c("a", "b", "c"))
c<-factor(c("b", "a", "c"))

what I want is like:
  c x
1 b 2
2 a 1
3 c 3

which means, I use b as keys and vector a as values and I find values for c.

I used the following codes:
x<-c()
d<-data.frame(b,a)
for (each in 1:length(c)){   # i don't know why each in c did not work
  tmp<-d$a[d$b==c[each]]                                  # question 
  x<-append(x, levels(tmp)[as.integer(tmp)]) 
}

data.frame(c,x)

If someone has a better way to do it, please help!!

Also, I don't understand why I have to use levels() since w/o it, i
only added the index for levels in to x.

BTW, when b is like 60,000, the process is very slow. Should I use hash here?

Thanks,

Weiwei


-- 
Weiwei Shi, Ph.D

"Did you always know?"
"No, I did not. But I believed..."
---Matrix III




More information about the R-help mailing list