【问题标题】:sorting matrix in R when column name is string当列名是字符串时,R中的排序矩阵
【发布时间】:2017-08-04 19:08:58
【问题描述】:

我有一个包含 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

如何重新排列整个矩阵?

谢谢!

【问题讨论】:

    标签: r sorting matrix


    【解决方案1】:

    首先让我们读入您的列名。

    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
    

    【讨论】:

    • 谢谢!这适用于整个数据集。
    【解决方案2】:
    # 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)];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      • 2016-10-23
      • 2020-12-16
      相关资源
      最近更新 更多