[R] how to (combine / recode / merge) two factor.

From: laurent buffat <laurent.buffat_at_free.fr>
Date: Wed 24 Aug 2005 - 02:50:30 EST

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

R-help@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 Received on Wed Aug 24 02:54:30 2005

This archive was generated by hypermail 2.1.8 : Fri 03 Mar 2006 - 03:39:55 EST