[R] creating unique and sorted values by combining columns

Alexander.Herr at csiro.au Alexander.Herr at csiro.au
Mon Aug 13 09:35:27 CEST 2007


 
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



More information about the R-help mailing list