基于r中的另一个向量,为向量中的每个元素排序字母

时间:2016-02-17 16:22:28

标签: r

我有一个矢量看起来像:

SNP <- c("A/G","A/C","A/C","T/C","A/G","A/C","T/G","T/C","A/C","T/G")

第二个向量(REF)是&#34; SNP&#34;中每个元素的两个字母之一的向量:

REF <- c("G","C","A","C","A","A","T","T","C","T")

我想在矢量&#34; SNP&#34;中添加每个元素的任何字母。如果匹配向量&#34; REF&#34;中的相应元素(字母),则在前面。 预期结果是:

SNP <- c("G/A","C/A","A/C","C/T","A/G","A/C","T/G","T/C","C/A","T/G")

2 个答案:

答案 0 :(得分:5)

您可以尝试:

mapply(function(x,y) paste(y,setdiff(x,y),sep="/"),
         strsplit(SNP,"/",fixed=TRUE),REF) 
#[1] "G/A" "C/A" "A/C" "C/T" "A/G" "A/C" "T/G" "T/C" "C/A" "T/G"

答案 1 :(得分:3)

这是另一种方式

m1 <- t(matrix(scan(text=SNP, sep='/', what='', 
                   quiet=TRUE),ncol=2, byrow=TRUE))
i1 <- t(t(m1)==REF)
paste(m1[i1], m1[!i1], sep='/')
#[1] "G/A" "C/A" "A/C" "C/T" "A/G" "A/C" "T/G" "T/C" "C/A" "T/G"