A 3D Random walk simulation
Quoting page 173:


  Another obvious generalization is to allow the walker to move in three dimensions [...] For this simulation we have restricted the steps to be of unit length along either ±x, ±y, or ±z.


I think the author meant that at each time step the walker will walk in one of three random directions (x or y or z), not all three. Without making drastic changes to your code, you could replace this section:

 if (runif(1)&lt;0.5) x &lt;- x+1 else x &lt;- x-1
 if (runif(1)&lt;0.5) y &lt;- y+1 else y &lt;- y-1
 if (runif(1)&lt;0.5) z &lt;- z+1 else z &lt;- z-1


with the following:

  direction &lt;- sample(c("x", "y", "z"), 1)
  if (direction == "x") { if (runif(1)&lt;0.5) x &lt;- x+1 else x &lt;- x-1 }
  if (direction == "y") { if (runif(1)&lt;0.5) y &lt;- y+1 else y &lt;- y-1 }
  if (direction == "z") { if (runif(1)&lt;0.5) z &lt;- z+1 else z &lt;- z-1 }


With this change, the slope is approximately 1, as shown in Figure 7.11.