Olha Kholod
Olha Kholod

Reputation: 559

sorting matrix in R when column name is string

I have a matrix with 300 columns, where rows correspond to gene counts and columns correspond to sample name. R order columns in following format:

sample59 sample6 sample60 sample61 sample62 sample63 sample64 sample65
[1,]  2       679.567      361        2       17        0        0        0
[2,]  0       0.000        0        0        0        0        0        0
[3,]  0       0.000        0        0        0        0        0        0
[4,]  0       0.000        0        0        0        0        0        0
[5,]  0       0.000    0        0        0        0        0        0
[6,]  0       0.000    0        0        0        0        0        0

I would like to format matrix like this:

sample6 sample59 sample60 sample61 sample62 sample63 sample64 sample65
[1,]  679.567       2      361        2       17        0        0        0
[2,]    0.000       0        0        0        0        0        0        0
[3,]    0.000       0        0        0        0        0        0        0
[4,]    0.000       0        0        0        0        0        0        0
[5,]    0.000       0        0        0        0        0        0        0
[6,]    0.000       0        0        0        0        0        0        0

How I can reorder the whole matrix?

Thank you!

Upvotes: 0

Views: 255

Answers (2)

Rui Barradas
Rui Barradas

Reputation: 76402

First let's read in your column names.

cnames <- scan(what = "character", text ="
sample59 sample6 sample60 sample61 sample62 sample63 sample64 sample65")

Now let's solve the column order problem, with some fake matrix.

library(stringr)

mat <- matrix(1:80, ncol = 8)
colnames(mat) <- cnames

icol <- str_order(colnames(mat), numeric = TRUE)
mat2 <- mat[, icol]
mat2

Upvotes: 2

Bruno Zamengo
Bruno Zamengo

Reputation: 860

# get column names of your dataframe (called df) and remove the "sample" word
n = sub("sample", "", names(df));
# and convert n to numbers (as they are, right?)
n = as.numeric(n)

# reorder your data.frame column depending on the n sorting
df = df[, order(n)];

Upvotes: 2

Related Questions