While loop with sampling until object takes on one of select values

I am trying to set up a process using a while loop in order to have my code consistently sample among certain xd[i] before one particular xd[i] becomes equal to x.

I know it would be more efficient to put everything under one for loop (except for the while loop) but I am trying to create this step by step. Right now, I am stuck on the while loop part. I cannot run that part of the code without R crashing, or if it does not crash, it seems to continue sampling nonstop until I manually stop it. How can I change my while loop such that it samples over the xd vector until one of the elements of xd matches with x?

Thank you

reset1 = {

a = 0.3 #lower legal threshold 

b = 0.9 #upper legal threshold

x = 0  

theta = runif(1,min = a, max = b)

A = 5 ## monetary value of harm from 

maxw = 2*A

minw = 0

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

xd = c(1,2,3)

w = c(1,2,3)

for (i in 1:length(xd)){w[i] = runif(1, min = 0, max = 2)} #trying to make it create a w for each person

##Drivers problem: pick the x that will minimize your cost

for(i in 1:length(xd)){xd[i] = min(c(1-(w[i]/(2*A)),((2+b)-sqrt(b^2-2*b+1+3*(w[i]/A)*(b-a)))/3,b))}


for(i in 1:length(xd)){proba = function(xd){(xd-1)^2}}  
proba(xd)   #ith individual probability of getting in an accident given their xd[i]

probn = 1 - proba(xd)      #probability of not getting in an accident given driveri's effort level

while (any(x!=xd)) {x = sample(c(xd[c(1,2,3)],0,0,0),size = 1, replace = TRUE, prob = c(proba(xd), probn)) ###the x is selected based on which ever x resulted in an accident   



This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.