R中的模拟使用概率

时间:2017-05-24 17:05:18

标签: r random

myfunction3 <- function(seq2,z)


for(j in 1:100)

{

if(z[j]>0.7)

{  
if(seq2[j] =='A')  replace(seq2,j,sample(c("C","G","T"),1))

else if(seq2[j] =='G')  replace(seq2,j,sample(c("C","A","T"),1))

else if(seq2[j] =='T')  replace(seq2,j,sample(c("C","G","A"),1))

else if(seq2[j] =='C')  replace(seq2,j,sample(c("A","G","T"),1))

else if(seq2[j]=='E')   replace(seq2,j,'T')

}

}

return(seq2)

我已经根据概率向量z编写了这个函数来模拟给定的DNA序列seq2,其中如果概率大于0.7,则新序列可以具有任何其他三个核苷酸(A,G,T,C)在它的位置。但每次它返回一个NULL向量。

2 个答案:

答案 0 :(得分:1)

以下是您的功能的紧凑变体:

myfunction3 <- function(seq2,z) {
    for(j in which(z>0.7))
    seq2[j] <- switch(seq2[j], 
                      A=sample(c("C","G","T"),1), 
                      G=sample(c("C","A","T"),1),
                      T=sample(c("C","G","A"),1),
                      C=sample(c("A","G","T"),1),
                      E="T"
    )
    return(seq2)
}

以下是它的工作原理:

set.seed(42)
z <- sample(1:10)/10
seq <- sample(c("A","G","T", "C"), 10, repl=TRUE)
data.frame(seq, z, seq2=myfunction3(seq,z))
#    seq   z seq2
# 1    G 1.0    T
# 2    T 0.9    C
# 3    C 0.3    C
# 4    G 0.6    G
# 5    G 0.4    G
# 6    C 0.8    T
# 7    C 0.5    C
# 8    A 0.1    A
# 9    G 0.2    G
# 10   T 0.7    T

测试最后一个条件(E =“T”):

set.seed(42)
z <- sample(3:17)/10
seq <- sample(c("A","G","T", "C", "E"), length(z), repl=TRUE)
data.frame(seq, z, seq2=myfunction3(seq,z))

答案 1 :(得分:1)

我假设seq2是一个字符向量,z是样本长度的向量,并且您希望改变seq2z > 0.7 <的位置/ p>

这样做的一种方法是首先创建一个有效替换的列表,由核苷酸键入,然后写一个变异函数,然后sapply函数到seq2的子向量,其中{{1} }}:

z > 0.7

例如:

substitutions <- list(A = c("C","G","T"),
                   G = c("A","C","T"),
                   T = c("A","C","G"),
                   C = c("A","G","T"),
                   E = c("T"))

mutate <- function(nucleotide){
  sample(substitutions[[nucleotide]],1)
}

myfunc <- function(seq2,z){
  to.change <- which(z > 0.7)
  seq2[to.change] <- sapply(seq2[to.change],mutate)
  seq2
}