[R] how to (combine / recode / merge) two factor.
laurent buffat
laurent.buffat at free.fr
Tue Aug 23 18:50:30 CEST 2005
Hi,
I have a data frame with two factors, and I would like to create a new
one by "combining" them.
I have already a solution, but it is very "heavy", and I'm sure there is
a basic function which can do the same.
I tried to find it in the R-help, but without result.
See the example :
# just to create a dataframe
f1 <- factor(rep(c("A","B"),3))
f2 <- factor(rep(c("x","y","z"),each=2))
df <- data.frame(f1,f2)
df <- rbind(df,df,df)
# here is what I want do do :
df$f1f2 <-
factor(as.numeric(df$f1)+(as.numeric(df$f2)-1)*nlevels(df$f1), labels=
letters[1:(nlevels(df$f1)*nlevels(df$f2))])
# I don't care about the labels.
df :
> df
f1 f2 f1f2
1 A x a
2 B x b
3 A y c
4 B y d
5 A z e
6 B z f
11 A x a
21 B x b
31 A y c
41 B y d
51 A z e
61 B z f
12 A x a
22 B x b
32 A y c
42 B y d
52 A z e
62 B z f
>
Thanks for your helps,
Laurent Buffat
More information about the R-help
mailing list