-2

I am looking to order my columns by name. I know that I can do the following: portManDMA = portManDMA[,c(1,2,6,7,8,9,10,3,4,5,11,12,13,14,15,16,17,18,19)] to reorder the columns, but what I would like to do is actually use the column name in the ordering. For example:

## OriginalMatrix  
DEF ABC KLM  HIJ

Where each 3 letters represent a column name. I would like then reorder them based on the columns names, something like portManDMA = portManDMA[,c("ABC","KLM","DEF","HIJ")], for example, so that the new ordering would then be:

## NewMatrix  
ABC KLM DEF HIJ  

Would anyone be able to help me with this?

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Mike
  • 1,049
  • 5
  • 20
  • 46
  • @AnandaMahto, No, I'm trying to order the columns by the column names, where the column names are "ABC", "KLM", "DEF" and "HIJ". When I try using the above code, it doesn't sort the data as I'd like. Thanks – Mike Dec 05 '13 at 15:14
  • 1
    Eh!? `portManDMA = portManDMA[,c("ABC","KLM","DEF","HIJ")]` *is* the answer, just look at @gung's updated Answer. If that isn't giving you what you want then you aren't telling us something important. As others have asked, please give a reproducible example and show what isn't working for you (i.e. *actual* code) – Gavin Simpson Dec 05 '13 at 15:22

2 Answers2

3

One possibility :

portManDMA[,sort(colnames(portManDMA))]

HTH

droopy
  • 2,788
  • 1
  • 14
  • 12
3

You can conveniently access the column (variable) names in a data frame (or matrix) with ?colnames. Once you have that, you can get a new ordering like the one you list at the beginning of your question with ?order (there is more on how to understand order() in this SO thread: Understanding the order() function). Here is a way to do this with your example:

> portManDMA <- read.table(text="DEF ABC KLM  HIJ
+ 1 2 1 3
+ 3 5 9 4", header=TRUE)
> portManDMA
  DEF ABC KLM HIJ
1   1   2   1   3
2   3   5   9   4
> new.order  <- order(colnames(portManDMA))
> new.order
[1] 2 1 4 3
> portManDMA <- portManDMA[, new.order]
> portManDMA
  ABC DEF HIJ KLM
1   2   1   3   1
2   5   3   4   9

Sorry about the alphabetical assumption, your code worked fine for me:

> portManDMA <- portManDMA[,c("ABC","KLM","DEF","HIJ")]
> portManDMA
  ABC KLM DEF HIJ
1   2   1   1   3
2   5   9   3   4
Community
  • 1
  • 1
gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79
  • Thanks for the reply. This won't work for me, as the ordering isn't necessarily in alphabetical order. Thanks again – Mike Dec 05 '13 at 15:15
  • Sorry, I must have read your question too fast. If you aren't asking for a convenient way to get them in alphabetical order, what are you asking for? You have a method for reordering listed in your question, you just have to do it manually, if it isn't alphabetical. – gung - Reinstate Monica Dec 05 '13 at 15:17