n <- 10 dirs <- sample(c("L","R","S"), n-1, replace=T) ## Initial position pos <- c(1, 0) ## Initial displacement displ <- c(1,0) ## Begin the plot plot(NULL,type=NULL,xlim=c(-n,n),ylim=c(-n,n),xlab='x',ylab='y') myColors <- palette(rainbow(n)) ## Initialize path to contain the first segment path <- cbind(pos) ## Plot initial position points(pos[1], pos[2], col=myColors[0],pch=19) for(i in 1:length(dirs)) { dir <- dirs[i]; ## Compute new displacement if( all.equal(displ, c(1,0)) == TRUE) { if (dir == "L") { displ <- c(0,1) } else if(dir=="R") { displ <- c(0,-1) } } else if( all.equal(displ, c(0,1)) == TRUE) { if (dir == "L") { displ <- c(-1,0) } else if(dir=="R") { displ <- c(1,0) } } else if( all.equal(displ, c(-1,0)) == TRUE) { if (dir == "L") { displ <- c(0,-1) } else if(dir=="R") { displ <- c(0,1) } } else if( all.equal(displ, c(0,-1)) == TRUE) { if (dir == "L") { displ <- c(1,0) } else if(dir=="R") { displ <- c(-1,0) } } ## Add new displacement to position pos <- pos + displ path <- cbind(path, pos) ## Plot current position in the i-th color points(pos[1], pos[2], col=myColors[i], pch=19) } ## Plot the path lines(t(path),type="l",lwd=2,col="magenta") #grid(nx=2*n, ny=2*n) ## Draw grid manually for (x in -n:n) lines(c(x,x),c(-n,n), col="gray",lty=2) for (y in -n:n) lines(c(-n,n),c(y,y), col="gray",lty=2)