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

Chuck Cleland ccleland at optonline.net
Tue Aug 23 18:55:24 CEST 2005


interaction(df$f1, df$f2)

?interaction

laurent buffat wrote:
> 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
> 
> ______________________________________________
> 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
> 
> 

-- 
Chuck Cleland, Ph.D.
NDRI, Inc.
71 West 23rd Street, 8th floor
New York, NY 10010
tel: (212) 845-4495 (Tu, Th)
tel: (732) 452-1424 (M, W, F)
fax: (917) 438-0894




More information about the R-help mailing list