Background:
I have a function called "GGG". This function shows where any number of players (argument: n.Players) on a sports field end up being at any Step (argument: Step) given total number of steps (argument: n.Steps) planned for players to take.
Each player's direction movement depends on a random number that can either be negative or positive. If positive, the player will go right from zero point on x-axis. If negative, player will go left from zero point on x-axis.
I'm providing the R code below, please run to see how it works.
Coding question:
My goal is that when there are plenty of players (e.g., 200 players), most of them populate the center line ("0", please see the picture below). Currently, I only achieve this when the value for the argument Step is an even number.
But I'm wondering how I can change my R code such that when argument Step is an "Odd number" ALSO most players populate the center line ("0" on the x-axis)?
(A) When "Step" is an even number (desired situation):
(B) When "Step" is an odd number (UNdesired situation):
GGG = function(Step, n.Players, n.Steps) {
plot(-9:9, -9:9, ty = "n", ann = F)
x <- rep(0, n.Players) ## Initial position of players
y <- seq(from = -9, to = 9, len = n.Players) ## y-position for players
## Sample movement of players:
xStepsMx <- matrix(sample(c(-1, 1), n.Players*n.Steps, replace = TRUE),
nrow = n.Players, ncol = n.Steps)
## Position of players:
xPosMx <- t(sapply(1:nrow(xStepsMx), function(ii) cumsum(xStepsMx[ii,]))) + x
abline(v = 0, col = 'red', lty = 2)
positions = if (Step > 0){ xPosMx[,Step] } else { x }
points(positions, y, cex = 7, lwd = 3, pch = 21, bg = "white")
text(positions, y, 1:n.Players, font = 2, cex = 1.5)
}
GGG(Step = 16, n.Players = 200, n.Steps = 16)
## Now change "Step" to any "odd" number like "15"
GGG(Step = 15, n.Players = 200, n.Steps = 16)
Aucun commentaire:
Enregistrer un commentaire