简体   繁体   中英

Scatter plot in R

I am teaching myself R by re-doing some assignments in my Monte Carlo class. I built a RANDU generator in R and I am tasked with for all triplets in the sequence (u_i,u_{i+1},u_{i+2}), in which 0.5 <= u_{i+1} <= 0.51, plot u_i versus u_{i+2}.

I did the following in MATLAB during the class and I get this:

在此处输入图片说明

Here is the code I wrote in Latex, just note that the data stored in variable u are simply uniform random numbers between 0 and 1.

在此处输入图片说明

Now to my issue, I get this error in R

Error in if (0.5 <= u[i + 1] & u[i + 1] <= 0.51) { : 
  missing value where TRUE/FALSE needed

I am not sure what the problem is here, here is my full R code:

n = 20002
x <- 1:n
x[1] = 1

for(i in 2:n){
  x[i] = (65539*x[i-1]) %% 2^31
}

u <- 1:n
u[1] = 1/(2^31)
for(i in 2:n){
  u[i] = x[i]/(2^31)
}


for(i in 1:length(u)){
  if(0.5 <= u[i+1] & u[i+1] <= 0.51){
    plot(u[i],u[i+2])
  }
}

Any suggestions are greatly appreciated.

I think the problem is for your last observation in u . As for your for loop you are asking to evaluate u[i+1] . Try this:

 for(i in 1:length(u)-1){
   if(0.5 <= u[i+1] & u[i+1] <= 0.51){
     plot(u[i],u[i+2])
   }
 }

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