首页 > 解决方案 > 在 R 中存储 For 循环的值然后绘图

问题描述

我正在尝试创建一个循环来存储xstar, x1[t], x2[t], x[t], a[t], and b[t]. 我的目标是最终绘制这些值并查看 x1 或 x2 是否收敛或接近xstar. 我正在努力设置它,以便我的代码以允许我绘制它的方式存储每个相关值。我也在努力设置它,以便在每次迭代结束时调整 a[t] 和 b[t]。下面是模型的播放顺序,以防直觉可能有助于说明我正在尝试做的事情。

随意跳到代码 *该模型在审查和解决争议的长期法庭和决定努力程度的一组侵权行为者之间进行模拟。游戏顺序如下:

  1. 法院设定了过失标准。这个疏忽标准是由法律先验设定的,但它共享其位置的初始信念 [a_t,b_t] ϵ [0,1]。

  2. N 个公民绘制 wi。每个人从 [0,10] 上的均匀分布中得出各自的努力/护理边际成本 wi。

  3. 公民 i 决定最佳努力水平 xi ϵ [0,1]。这一决定取决于他们的减排成本 (wi) 和现行法律 [a,b] 的状态。

  4. 事故有一定概率发生并导致法律纠纷。发生事故的概率是努力程度 xi 的递减函数。当事故发生时,伤害是有金钱价值的,A。我假设当事故发生时,审判/争议也会发生。

  5. 法院审查争议并评估努力程度。审查案件,法院了解该努力程度是否满足理想的过失标准。这个过程是没有成本的。

  6. 法院对案件的狭义或广义裁决作出裁决。合法阈值和 [a_t,b_t] 更新为 [a_(t+1),b_(t+1),其中 a_(t+1) 或 b_(t+1)=x_i

  7. 重复从第 3 阶段开始*

period = c(1:5)   ## Number of periods in the iteration of the loop.
reset1 = {
  a = c() #lower bound of belief in xstar 
  b = c() #upper bound of belief in xstar
  A = 5 ## monetary value of harm from 

  maxw = 3
  minw = 0
  wbar = (maxw+minw)/2  ##average cost

  xstar = 1 - wbar/(2*A) 
  xstar

  x1 = c()
  x2 = c()
  x  = c()

  w1 = runif(1,min = 0, max = 3)
  w2 = runif(1,min = 0, max = 3)

if(t==1){a[t]=0.3;b[t]=0.95}

}

for (t in 1:length(period)) {

  x[t] = 0 

  ##Tortfeasors problem: pick the x that will minimize your cost --- piecewise optimization. First object is if (x<=a), second is if (a<x<b), and third is when (x>=b).

x1[t] = min(c(1-(w1/(2*A)),((2+b[t])-sqrt(b[t]^2-2*b[t]+1+3*(w1/A)*(b[t]-a[t])))/3,b[t])) 

x2[t] = min(c(1-(w2/(2*A)),((2+b[t])-sqrt(b[t]^2-2*b[t]+1+3*(w2/A)*(b[t]-a[t])))/3,b[t]))

  proba1 = function(x1){(x1[t]-1)^2}  #probability of accident only given driver1's effort level.
  proba1(x1)
  probn1 = 1 - proba1(x1)      #probability of not getting in an accident given driver1's effort level
  probn1

  proba2 = function(x2){(x2[t]-1)^2}  
  proba2(x2)
  probn2= 1 - proba2(x2)
  probn2

  while (x[t]!=x1[t] & x[t]!=x2[t]) {
        x[t] = sample(c(x1[t],x2[t], 0,0),size = 1, replace = TRUE, prob = c(proba1(x1),proba2(x2), probn1, probn2)) 
        ###the x is selected based on which ever x resulted in an accident   
  }
  show(x[t])   

  rulings = if(x[t]>=b[t]) {
                ruling = print("Not Negligent")              
  } else if(x[t]<=a[t]) {
                ruling = print("Negligent")               
  } else if(x[t]>a[t] & x[t]<b[t]) {
       ruling = if(x[t]<xstar){"guilty"
  } else if(x[t]>=xstar){"not guilty"}
    show(ruling)}  


  ##legal adjustment and updating of beliefs in ambiguous region after discovery of liability
  if(ruling == "guilty") {a[t+1] = x[t]; b[t+1] = b[t]} 
  else if (ruling == "not guilty") {b[t+1] = x[t]; a[t+1]=a[t]} 
  else {a[t+1]=a[t]; b[t+1] = b[t];print("beliefs unchanged")}       
}

标签: rloopsplot

解决方案


推荐阅读