0

I have a matrix already set and I am trying to sort it in order of sample id and its associated number.

I have sample id's in mixed order from V1-V26 and I want the matrix to be in the order of V1-V26 and not mixed. How can I sort the matrix in R by the first column of sample id's in ascending order?

Update with second code

r<-read.table("testbray.csv", header = TRUE, sep = ",", check.names = FALSE)
i1 <- as.numeric(sub("\\D+", "", row.names(r)))
j1 <- as.numeric(sub("\\D+", "", colnames(r)))
y<-r[order(i1), order(j1)]

>

 dput(head(r[, c(1, 3)]))
structure(list(structure(c(16L, 12L, 3L, 17L, 5L, 22L), .Label = c("V1", 
"V10", "V11", "V12", "V13", "V14", "V15", "V17", "V18", "V19", 
"V2", "V20", "V21", "V22", "V23", "V24", "V25", "V26", "V27", 
"V3", "V4", "V5", "V6", "V7", "V8", "V9"), class = "factor"), 
    V20 = c(0.592334495, 0, 0.893728223, 0.625048393, 0.587882307, 
    0.647502904)), row.names = c(NA, 6L), class = "data.frame")

twhitney
  • 25
  • 5
  • Please add data using `dput` and not as screenshots. Please read the info about [how to ask a good question](http://stackoverflow.com/help/how-to-ask) and how to give a [reproducible example](http://stackoverflow.com/questions/5963269) – Ronak Shah Jan 05 '20 at 04:05
  • I get your column names as `colnames(r)# [1] "" "20"` which is not the one you showed from `V1`, `V2` etc – akrun Jan 05 '20 at 21:05

1 Answers1

0

We can use gtools::mixedsort

m1[mixedsort(row.names(m1)), mixedsort(colnames(m1))]

Or another option is to use base R by removing the 'V' with sub convert to integer and order

i1 <- as.numeric(sub("\\D+", "", row.names(m1)))
j1 <- as.numeric(sub("\\D+", "", colnames(m1)))
m1[order(i1), order(j1)]
akrun
  • 874,273
  • 37
  • 540
  • 662
  • Both ways are successfully sorting the row, but not the column. It is assigning numbers to the column and those are sorted but not the V1-V26. I think it may have to do with how I am importing the table? This is my code: r<-read.table("testbray.csv", header = TRUE, sep = ",", check.names = FALSE) library(gtools) x<- r[mixedsort(row.names(r)), mixedsort(colnames(r))] i1 <- as.numeric(sub("\\D+", "", row.names(r))) j1 <- as.numeric(sub("\\D+", "", colnames(r))) y<-r[order(i1), order(j1)] – twhitney Jan 05 '20 at 17:53
  • @twitney Can you please update your post with the `dput` of the small example – akrun Jan 05 '20 at 19:48
  • @twhitney can you sshow `dput` of the data to get the structure correctly an your expected output – akrun Jan 05 '20 at 19:59
  • sorry I misread your comment...not sure if this is what you are asking for – twhitney Jan 05 '20 at 21:03
  • @twhitney Based on the strucutre you showed, it is not having any 'V' in the column name or row name – akrun Jan 05 '20 at 21:05
  • @twhitney Now, it is not the rownames that aree 'V24', ''V20', but it is the first column, and there is no column name for that. So, I guess it is the data structure that is not correcct – akrun Jan 05 '20 at 21:42