Julio Diaz
Julio Diaz

Reputation: 9437

First column as header in R table

Is there a way to turn the first column of a table into a header? For instance, given this table obtained with the following script:

 test <- as.matrix(read.csv(file="fileName.csv", sep=",", head=FALSE))

  [1,]  72 6467280
  [2,]  71 1066945
  [3,] 143 1128764
  [4,]  69  420286
  [5,] 141  137259
  [6,] 144 2845182
  [7,] 142  151408
  [8,]  61   19805
  [9,]  52    7520
 [10,] 124    3983

I would like to obtain a table where the first column is the label, and be able to rearrange the table according to these values. So I would get something like this.

  [52,]  7520
  [61,]  19805
  [69,]  420286
  [71,]  1066945
  [72,]  6467280
  [124,] 3983
  [141,] 137259
  [142,] 151408
  [143,] 1128764
  [144,] 2845182

Thanks

Upvotes: 1

Views: 14363

Answers (1)

Alex Reynolds
Alex Reynolds

Reputation: 96984

After renaming the rows, you can retrieve them with row.names(), applying the desired sort:

> test <- as.matrix(read.csv("http://dl.dropbox.com/u/31495717/stackoverlow.orderlist.csv", sep=",", head=FALSE))
> rownames(test) <- test[,1]
> test <- test[order(as.numeric(row.names(test)), decreasing=FALSE),]
> test <- test[,-1]
> as.matrix(test)
       [,1]
52     7520
61    19805
69   420286
71  1066945
72  6467280
124    3983
141  137259
142  151408
143 1128764
144 2845182

Upvotes: 6

Related Questions