Skip to content

factor vector manipulation

2 messages · Weiwei Shi, Gabor Grothendieck

#
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
#
On 6/3/05, Weiwei Shi <helprhelp at gmail.com> wrote:
cbind(c, x = a[match(c,b)])