[R] How to compare X1 = X2 = ... = Xn?

Sundar Dorai-Raj sundar.dorai-raj at PDF.COM
Mon Jul 19 20:03:39 CEST 2004



F Duan wrote:

> Dear All,
> 
>  
> 
> I have a data frame with n columns: X1, X2, ., Xn. Now I want to create a
> new column: if X1 = X2 = . = Xn, the value is 1; Otherwise, the value is 0.
> 
>  
> 
> How to do that in a quick way instead of doing (n choose 2) comparisons? 
> 
>  
> 
> Thank you,
> 
>  
> 
> Frank
> 
> 

How about something like?

x <- data.frame(X1 = c(1, 1, 2, 4),
                 X2 = c(4, 1, 2, 5),
                 X3 = c(2, 1, 2, 2))
nuniq <- function(x) length(unique(x))
as.numeric(apply(as.matrix(x), 1, nuniq) == 1)

--sundar




More information about the R-help mailing list