[R] Ordering a matrix (and not losing the rownames)

arun smartpink111 at yahoo.com
Fri Aug 30 15:27:52 CEST 2013


Hi Ramón,
May be this helps:
tags_totals<-matrix(c(15,11,23,7,5),ncol=1,dimnames=list(c("Wikis","Glosarios","Grupos","Bases de datos","Taller"),NULL))

tags_totals[order(tags_totals[,1],decreasing=TRUE),,drop=FALSE]
#               [,1]
#Grupos           23
#Wikis            15
#Glosarios        11
#Bases de datos    7
#Taller            5

A.K.



Hello, 

I have a matrix like this: 

> tags_totals 
               [,1] 
Wikis            15 
Glosarios        11 
Grupos           23 
Bases de datos    7 
Taller            5 

And I want to order by the value of the first column. I do this: 

ordered_matrix <- as.matrix(tags_totals[order(tags_totals[,1],decreasing=TRUE)]) 

It orders alright, but I lose the rownames, that I need for the graphics 
> ordered_matrix 
     [,1] 
[1,]   23 
[2,]   15 
[3,]   11 
[4,]    7 
[5,]    5 

> rownames(ordered_matrix) 
NULL 

If I try to do it after converting to a dataframe I get an error that I don't understand: 

> tags_totals_frame <- as.data.frame(tags_totals) 
> tags_totals_frame[,1] 
[1] 15 11 23  7  5 
> ordered_frame <- tags_totals_frame[order(tags_totals_frame[,1],decreasing=TRUE)] 
Error en `[.data.frame`(tags_totals_frame, order(tags_totals_frame[, 1],  : 
  undefined columns selected 

Thanks on any help, 

-- 
================================== 
Ramón Ovelar 
Campus Virtual Birtuala UPV/EHU 
Tel: (34) 94 601 3407 
http://campusvirtual.ehu.es




More information about the R-help mailing list