2013-12-11 61 views
0

我想解決這個問題:建設與線路信息的矩陣

我想以這種格式轉換:

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

您的數據:

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 s爲適當表示丟失的數據。但是你可以通過X s的以下命令替換NA S:

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相當於斯文的回答(+1,斯文):

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如果必要的話也可以採取同樣的方式