简体   繁体   中英

Simulations in R using probability

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)

I have written this function to simulate a given DNA sequence seq2 according to the probability vector z in which if the probability is greater than 0.7 then the new sequence can have any of the other three nucleotides(A,G,T,C) in its place. But everytime it is returning a NULL vector.

Here is a compact variant of your function:

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)
}

Here is how it works:

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

Testing the last condition (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))

I assume that seq2 is a character vector and that z is a vector of the sample length and that you want to mutate the positions in seq2 where z > 0.7

One way to do it is to first create a list of valid substitutions, keyed by the nucleotides, then write a mutation function, then sapply that function to the subvector of seq2 where 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
}

For example:

> s <- sample(c("A","T","G","C","E"),10, replace = T)
> z <- sample(c(0,0.8),10, replace = T)
> rbind(s,z,myfunc(s,z))
  [,1]  [,2] [,3] [,4]  [,5] [,6]  [,7]  [,8]  [,9] [,10]
s "E"   "A"  "C"  "G"   "E"  "C"   "E"   "T"   "E"  "A"  
z "0.8" "0"  "0"  "0.8" "0"  "0.8" "0.8" "0.8" "0"  "0.8"
  "T"   "A"  "C"  "C"   "E"  "A"   "T"   "G"   "E"  "T"  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM