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

Jim Lemon bitwrit at ozemail.com.au
Tue Jul 20 11:49:27 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?
>
Assuming that the Xs are numeric, and your data frame is named data.df:

data.df$newcol<-
as.numeric(apply(as.matrix(my.df),1,function(x) return(length(unique(x))==1)))

Jim




More information about the R-help mailing list