【问题标题】:Construct a matrix with lines information用线条信息构造一个矩阵
【发布时间】:2013-12-11 15:25:43
【问题描述】:

我想解决这个问题:

我想转换那种格式:

Samples Genotype  Region 
sample1    A      Region1
sample1    B      Region2
sample1    A      Region3
sample2    A      Region2
sample2    B      Region3
sample3    B      Region1
sample3    A      Region3

到基因型矩阵,包括缺失基因型的标签:

Samples   Region1 Region2 Region3
sample1     A       B      A
sample2     X       A      B
sample3     B       X      A

可以在R软件中做吗? 非常感谢。

【问题讨论】:

    标签: r matrix lines reshape


    【解决方案1】:

    您的数据:

    dat <- read.table(text = "Samples Genotype  Region 
    sample1    A      Region1
    sample1    B      Region2
    sample1    A      Region3
    sample2    A      Region2
    sample2    B      Region3
    sample3    B      Region1
    sample3    A      Region3", header = TRUE)
    

    您可以使用reshape2 包。

    library(reshape2)
    dat2 <- dcast(dat, Samples ~ Region, value.var = "Genotype")
    

    结果中,缺失值用NA表示:

    #   Samples Region1 Region2 Region3
    # 1 sample1       A       B       A
    # 2 sample2    <NA>       A       B
    # 3 sample3       B    <NA>       A
    

    NAs 适合表示缺失数据。但是您可以使用以下命令将NAs 替换为Xs:

    dat2[is.na(dat2)] <- "X"
    
    #   Samples Region1 Region2 Region3
    # 1 sample1       A       B       A
    # 2 sample2       X       A       B
    # 3 sample3       B       X       A
    

    【讨论】:

      【解决方案2】:

      这是“基本 R”reshape 相当于 Sven 的答案(+1,Sven):

      reshape(dat, direction = "wide", idvar = "Samples", timevar="Region")
      #   Samples Genotype.Region1 Genotype.Region2 Genotype.Region3
      # 1 sample1                A                B                A
      # 4 sample2             <NA>                A                B
      # 6 sample3                B             <NA>                A
      

      如有必要,请以相同的方式替换NA

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-07-03
        • 2019-05-13
        • 1970-01-01
        • 2017-11-26
        • 2012-02-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多