簡體   English   中英

當列名是字符串時 R 中的排序矩陣

[英]sorting matrix in R when column name is string

我有一個包含 300 列的矩陣,其中行對應於基因計數,列對應於樣本名稱。 R 以下列格式對列進行排序:

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

我想像這樣格式化矩陣:

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

我如何重新排序整個矩陣?

謝謝!

# 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)];

首先讓我們讀入您的列名。

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

現在讓我們用一些假矩陣來解決列順序問題。

library(stringr)

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM