Alexander.Herr at csiro.au
2007-Aug-13 07:35 UTC
[R] creating unique and sorted values by combining columns
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
Jacques VESLOT
2007-Aug-13 08:26 UTC
[R] creating unique and sorted values by combining columns
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. >