Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

This is a question about fundamental of R Studio, I have this following code, ##

ID: 3842532 • Letter: T

Question

This is a question about fundamental of R Studio,

I have this following code,

####################################################################

# finding the value of t(i)
sig<-5
tau<-1
ttotal<-10 # ~ 9.9999
r<--20:20
lam<-runif(1,0); # generate initial value of lambda
print(lam)
Pi<-pnorm((r+.5)/sig)-pnorm((r-.5)/sig) # given formula for probability in i cell

DM1<-c(rep(0,19),Pi[20:22]*(1-exp((-10/3)/1)),rep(0,19)) # calculate detected mass 3 adjacent cells
DM2<-c(rep(0,18),Pi[19:23]*(1-exp((-10/5)/1)),rep(0,18)) # calculate detected mass 5 adjacent cells
DM3<-c(rep(0,17),Pi[18:24]*(1-exp((-10/7)/1)),rep(0,17)) # calculate detected mass 7 adjacent cells
DM4<-c(rep(0,16),Pi[17:25]*(1-exp((-10/9)/1)),rep(0,16)) # calculate detected mass 9 adjacent cells
DM5<-c(rep(0,15),Pi[16:26]*(1-exp((-10/11)/1)),rep(0,15)) # calculate detected mass 11 adjacent cells <== peak
DM6<-c(rep(0,14),Pi[15:27]*(1-exp((-10/13)/1)),rep(0,14)) # calculate detected mass 13 adjacent cells

####################################################################

as you see there are some repetitions in my code, and I want to make it simpler by using a "for loop".

Any help is deeply appreciated.

Explanation / Answer

Lets firstly identify the part on your code where we can put into a for loop:

This part looks to be repeating.

DM1<-c(rep(0,19),Pi[20:22]*(1-exp((-10/3)/1)),rep(0,19)) # calculate detected mass 3 adjacent cells
DM2<-c(rep(0,18),Pi[19:23]*(1-exp((-10/5)/1)),rep(0,18)) # calculate detected mass 5 adjacent cells
DM3<-c(rep(0,17),Pi[18:24]*(1-exp((-10/7)/1)),rep(0,17)) # calculate detected mass 7 adjacent cells
DM4<-c(rep(0,16),Pi[17:25]*(1-exp((-10/9)/1)),rep(0,16)) # calculate detected mass 9 adjacent cells
DM5<-c(rep(0,15),Pi[16:26]*(1-exp((-10/11)/1)),rep(0,15)) # calculate detected mass 11 adjacent cells
DM6<-c(rep(0,14),Pi[15:27]*(1-exp((-10/13)/1)),rep(0,14)) # calculate detected mass 13 adjacent cells

The highlighted one's(bolded) can be replaced by loop variables like:

for(i in 0:5)
{
m <- 20L;
   j <- 19L;
   k <- 3L;
   l <- 22L;
  
   DM1(i+1)<-c(rep(0,(j-i)),Pi[(m-i):l+i]*(1-exp((-10/(k+(i%2)+(i%2)))/1)),rep(0,(j-i)))
}

I have just used mathematical calculation, for each ith value from 0 to 5, just add or subtract.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote