Reputation: 1
I want to test the useful life of two parts where one (part A) moves within the other (part B). There are 10 possible distinct "destinations" for Part A to land. Useful life is defined as 15,000 movements.
I've tried to generate a vector of "destinations" and eliminate having the same "destination" appear back-to-back. I can generate the vector but cannot figure out how to eliminate a back-to-back repeat. With acceptable output I can program a motor to step through each "destination" until useful life and test other mechanical attributes of both parts.
Here's my code:
iterations <- (50) ##just to test the code
LSVmin <- (1)
LSVmax <-(10)
movementV <- matrix(data=0, nrow=iterations, ncol=1) ##create vector for movement values
movementV[1,] <- 10
i <- 2
for (i in 2:iterations) {
movement1 <- (floor(runif(1, min=LSVmin, max=LSVmax)))
movementV[i, ] <- movement1
if (identical(movementV[i, ], movementV[i-1, ]) > 0)
movementV[i, ] <- movement1
else {
movement2 <- (floor(runif(1, min=LSVmin, max=LSVmax))) ##no provision for repeats
movementV[i, ] <- movement2
}
i<- (i + 1) ### iterate the loop
}
I've tried a number of methods to compare subsequent values but I don't know how to establish a variable within the if...else
routine and not lose it when the loop iterates.
Upvotes: 0
Views: 87
Reputation: 13
If I correctly understand what you want, I suggest you use the sample() function as follow:
iterations=50
LSVmin=1
LSVmax=10
posssibleChoices=c(LSVmin:LSVmax)
movement=rep(NA,iterations)
movement[1]=10
for(i in 2:iterations){
movement[i]=sample(posssibleChoices[-which(posssibleChoices==movement[i-1])],1)
}
movement
[1] 10 8 4 5 9 1 10 9 1 8 3 6 9 8 6 4 8 10 6 7 5 7 10 8 4 6 8
[28] 5 7 1 3 4 9 2 4 9 4 6 2 5 9 6 7 5 10 4 2 6 7 5
(1) Start with vector full of NA
(2) Initiate the first value of this vector to 10 (I kept this step because that is maybe something you want or need)
(3) For loop from 2 to iterations, sampling the new value in a vector containing all your possible choices (posssibleChoices) but not containing the lastest value from movement (movement[i-1])
PS: no need to increment i in the for loop, as it does it on its own (which is not the case for while loops of course).
Upvotes: 0
Reputation: 3438
Is this what you're after? If you want integers you can more easily use sample
rather than floor(runif(...))
. For each repetition, we sample a value from 1 to 10, then check that is not the same as the value in the previous index.
vals <- rep(0, 50)
for (i in seq_along(vals)) {
new <- sample(10, 1, replace = TRUE)
while (new == vals[max(i-1, 1)]) {
new <- sample(10, 1, replace = TRUE)
}
vals[i] <- new
}
vals
# [1] 5 1 2 6 3 4 6 7 5 4 8 9 8 4 2 8 1 4 8 2 4 9 4 7 2 10 3 2 9 10 3 8 6 10 1 5 3 1 10 1 5 10 3 7 1 10 2
# [48] 3 1 3
Upvotes: 1