用行信息构造矩阵

时间:2013-12-11 15:25:43

标签: r matrix lines reshape

我想解决这个问题:

我想转换那种格式:

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软件中做到吗? 非常感谢。

2 个答案:

答案 0 :(得分:2)

您的数据:

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

NA适合表示缺失的数据。但您可以使用以下命令将NA替换为X

dat2[is.na(dat2)] <- "X"

#   Samples Region1 Region2 Region3
# 1 sample1       A       B       A
# 2 sample2       X       A       B
# 3 sample3       B       X       A

答案 1 :(得分: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