<p>The question is clear and well formulated, so please don't take anything in this answer to be critical of your craftsmanship.  But when code doesn't do what you want it to do, there are two kinds of possibilities: the code is wrong (or there are bugs in the software platform); or the underlying concept is wrong (or the book was incorrect).</p>

<p>We address concepts here--the second kind of possibilities--and will tolerate a certain amount of code in the presentation of question when it's otherwise clear what needs to be addressed.  However, this particular question (a) employs a great deal of code--several pages; (b) relies heavily on the code to express itself; (c) has clear coding errors (some of which were addressed in comments); and (d) shows no evidence of having been checked or debugged: it does quite a lot in a few lines, just about any of which could be problematic.</p>

<p>On that basis I think this question would be more suitable for SO.  However, it might be closed there if there's a perception that the code does not offer a <em>minimal reproducible example.</em>   I find this (hard and fast) criterion to be useful here on CV, too: <strong>if we really must rely on code to understand and answer a question, then please make the code be as small, simple, and clear as possible.</strong>  Show what you have done to assure that its component calculations are correct, so that we can focus on the extent to which it implements the intended procedure.</p>

<p><strong>Another good criterion is this: if an effective answer is, or is likely to be, "read the manual page," then the question is not on topic here.</strong>  In reviewing the question I note that you are using R's <code>rnorm</code> function to generate Normal random variables in a way that is inconsistent with the ESL terminology: by "<span class="math-container">$N(0,6.25)$</span>" it means a Normal distribution of mean zero and <em>variance</em> <span class="math-container">$6.25,$</span> as indicated <em>inter alia</em> near Equation <span class="math-container">$(3.9)$</span> on p. 47, whereas R's <code>rnorm</code> uses the mean and <em>standard deviation</em> as arguments.  When the issue is that the function isn't being correctly called, arguably the problem is in the software, not the concepts.</p>
