Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 如何在数组上循环并在其他数组中存储操作值_R_Arrays_Loops_Plot - Fatal编程技术网

R 如何在数组上循环并在其他数组中存储操作值

R 如何在数组上循环并在其他数组中存储操作值,r,arrays,loops,plot,R,Arrays,Loops,Plot,为了绘制模式(近似错误,样本大小),我想在数组上循环(运行)以获得近似错误的4个值,当我尝试使用一个值时,它正在工作: 但当我开始使用数组时,我可以打印这些值,但我不能将结果存储在一个变量中,以便将所有值存储在所有变量中,如运行,以在绘图中显示它们,下面是我的代码: runs <- c(1000, 10000, 100000, 1000000) apro_err <- c() pi_real <- 3.14159265 for (i in runs){ #runif s

为了绘制模式(近似错误,样本大小),我想在数组上循环(运行)以获得近似错误的4个值,当我尝试使用一个值时,它正在工作:

但当我开始使用数组时,我可以打印这些值,但我不能将结果存储在一个变量中,以便将所有值存储在所有变量中,如运行,以在绘图中显示它们,下面是我的代码:

runs <- c(1000, 10000, 100000, 1000000)
apro_err <- c()
pi_real <- 3.14159265

for (i in runs){
  #runif samples from a uniform distribution
  xs <- runif(i,min=-0.5,max=0.5)
  ys <- runif(i,min=-0.5,max=0.5)
  in.circle <- xs^2 + ys^2 <= 0.5^2
  mc.pi <- (sum(in.circle)/i)*4
  absdif <- abs(mc.pi - pi_real)
  apro_err[i] <- absdif
  print(absdif)
  # plot(xs,ys,pch=".",col=ifelse(in.circle,"blue","red"),xlab='',ylab='',asp=1, main=paste("MC Approximation of Pi =",mc.pi))
}

plot(apro_err, runs, ylab='Approximation Error', xlab='Sample Size',col='red')

运行代码中的问题是,您使用
i
作为运行(
1000
…),然后使用相同的
i
存储在
apro\u err[i]

我重新格式化了代码,这样您就可以正确地存储值了。这允许您绘制四个点,每个运行大小一个点,而不是一个点

runs <- c(1000, 10000, 100000, 1000000)
apro_err <- c()

PI_REAL <- 3.14159265
UNI_MIN <- -0.5
UNI_MAX <- 0.5

for (i in seq_along(runs)){
  #runif samples from a uniform distribution
  run <- runs[i]
  xs <- runif(run, min = UNI_MIN, max = UNI_MAX)
  ys <- runif(run, min = UNI_MIN, max = UNI_MAX)
  in.circle <- xs^2 + ys^2 <= UNI_MAX^2
  mc.pi <- (sum(in.circle)/run) * 4
  absdif <- abs(mc.pi - PI_REAL)
  apro_err[i] <- absdif
  print(absdif)
  # plot(xs,ys,pch=".",col=ifelse(in.circle,"blue","red"),xlab='',ylab='',asp=1, main=paste("MC Approximation of Pi =",mc.pi))
}

plot(apro_err, runs, ylab='Approximation Error', xlab='Sample Size',col='red')

运行您希望在绘图中看到多少点?4点,运行的所有点(1000、10000、100000、1000000)及其结果,我在运行absdif:[1]0.00559265[1]0.020000735[1]0.00204735[1]0.00063135后打印,以便在绘图中进行比较:运行,absdif