0

I have a dataset with a large number of columns (+300). I am interested only in a few of them. I selected these in this way:

ks2reduced <- ks2data[,ks2meta[,2]]

where ks2meta[,2] contains the names of the columns I am interested in. This works but the problem is that the resulting data frame has the columns in a different order than the order set in ks2meta[,2]:

> ks2meta[,2]
[1] RECTYPE   LEA   ESTAB  URN SCHNAME            
[6] ..
> colnames(ks2reduced)
[1] "TAB1618"    "LEA"        "ALPHAIND"   "TKS1APS"    "TPUPYEAR"   "PBELIG"     "URN"        
[6] ..

I am, actually, surprised by this behaviour of R - to me it seems to be a "language gotcha" (behaviour that is probably explained but not expected). How can I select the columns in the same order as they are listed in a vector?

Nick
  • 2,924
  • 4
  • 36
  • 43
  • 2
    Please make it easier for people to help you by providing a [**minimal, reproducible example**](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example/5963610#5963610) – Henrik Mar 19 '14 at 09:35

1 Answers1

1

probably because your vector is a factor and not a character :

ks2reduced <- ks2data[,as.character(ks2meta[,2])]
droopy
  • 2,788
  • 1
  • 14
  • 12