[R] creating unique and sorted values by combining columns

Jacques VESLOT Jacques.Veslot at avignon.inra.fr
Mon Aug 13 10:26:24 CEST 2007


apply(tmp, 1, function(x) paste(sort(unique(x[x!=0])),collapse="_"))

Jacques VESLOT

INRA - Biostatistique & Processus Spatiaux
Site Agroparc 84914 Avignon Cedex 9, France

Tel: +33 (0) 4 32 72 21 58
Fax: +33 (0) 4 32 72 21 84



Alexander.Herr at csiro.au a écrit :
>  
> Hi List,
>
> I am combining column values of a dataframe to create a new variable
> that is the sorted and unqiue combination of the columns (and excluding
> 0). The following works, but surely there is a more elegant way of doing
> this?
>
> t1<-NULL
> for(i in 1:nrow(tmp)) {
>   if(i == 1){
>   sort(c(tmp[i,1], tmp[i,2],tmp[i,3],tmp[i,4],tmp[i,5]),
> decreasing=TRUE)->t1
>   }
>   else {
>    rbind(t1,sort(c(tmp[i,1],
> tmp[i,2],tmp[i,3],tmp[i,4],tmp[i,5]),decreasing=TRUE))->t1
>    }
> }
>
> t2<-NULL
> for(i in 1:nrow(t1)){
>  if(i == 1) paste(unique(t1[i,t1[i,]>0]),collapse="_")->t2
>  else cbind(t2,paste(unique(t1[i,t1[i,]>0]),collapse="_"))->t2
> }
>
> tmp
> t1
> t2
>
>
> Any hints appreciated.
> Thanks
> Herry
>
> ______________________________________________
> 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
> and provide commented, minimal, self-contained, reproducible code.
>



More information about the R-help mailing list