<p><div><div><div><div data-show-faces="false" data-height="21" data-width="100" data-layout="button_count" data-send="true" data-href="https://www.r-bloggers.com/power-analysis-and-sample-size-calculation-for-agriculture/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="http://r-video-tutorial.blogspot.com/2017/07/power-analysis-and-sample-size.html"> R tutorial for Spatial Statistics</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div></div>
<p>Power analysis is extremely important in statistics since it allows us to calculate how many chances we have of obtaining realistic results. Sometimes researchers tend to underestimate this aspect and they are just interested in obtaining significant p-values. The problem with this is that a significance level of 0.05 does not necessarily mean that what you are observing is real.<br>In the book “Statistics Done Wrong” by Alex Reinhart (which you can read for free here: <a rel="nofollow" href="https://www.statisticsdonewrong.com/" target="_blank">https://www.statisticsdonewrong.com/</a>) this problem is discussed with an example where we can clearly see that a significance of 0.05 does not mean that we have 5% chances of getting it wrong, but actually we have closer to 30% chances of obtaining unrealistic results. This is because there are two types of errors in which we can incur (for example when performing an ANOVA), the type I (i.e. rejecting a null hypothesis when it is actually true) and type II (i.e. accepting a null hypothesis when it is actually false).</p>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i2.wp.com/datasciencedojo.com/wp-content/uploads/type1and2error.gif?ssl=1" target="_blank"><img border="0" data-original-height="322" src="https://i2.wp.com/datasciencedojo.com/wp-content/uploads/type1and2error.gif?resize=450%2C322&ssl=1" data-recalc-dims="1" data-original-width="450"></a></td>
</tr>
<tr>
<td>Image taken from: https://datasciencedojo.com/</td>
</tr>
</tbody>
</table>
<p>The probability of incurring in a type I error is indicated by α (or significance level) and usually takes a value of 5%; this means that we are happy to consider a scenario where we have 5% chances of rejecting the null hypothesis when it is actually true. If we are not happy with this, we can further decrease this probability by decreasing the value of α (for example to 1%). On the contrary the probability of incurring in a type II error is expressed by β, which usually takes a value of 20% (meaning a power of 80%). This means we are happy to work assuming that we have a 20% chance of accepting the null hypothesis when it is actually false.<br>If our experiment is not designed properly we cannot be sure whether we actually incurred in one of these two errors. In other words, if we run a bad experiment and we obtain a insignificant p-value it may be that we incurred in a type II error, meaning that in reality our treatment works but its effect cannot be detected by our experiment. However, it may also be that we obtained a significant p-value but we incurred in a type I error, and if we repeat the experiment we will find different results.<br>The only way we can be sure to run a good experiment is by running a power analysis. By definition power is the probability of obtaining statistical significance (not necessarily a small p-value, but at least a realistic outcome). Power analysis can be used before an experiment to test whether our design has good chances of succeeding (<i>a priori</i>) or after to test whether the results we obtained were realistic.</p>
<p>
<h3>Effect Size</h3>
<div>A simple and effective definition of effect size is provided in the book “Power Analysis for Experimental Research” by Bausell &amp; Li. They say: </div>
<div>“effect size is nothing more than a standardized measure of the size of the mean difference(s) among the study’s groups or of the strength of the relationship(s) among its variables”.</div>
<div></div>
<div>Despite its simple definition the calculation of the effect size is not always straightforward and many indexes have been proposed over the years. Bausell &amp; Li propose the following definition, in line with what proposed by Cohen in his “Statistical Power Analysis for the Behavioral Sciences”:</div>
<div>
<div><a rel="nofollow" href="https://i1.wp.com/2.bp.blogspot.com/-ea4IXJm-ltc/WXHcCE7SBNI/AAAAAAAAXss/_kfSoMCXvjs38ARVuXiuSE4-7YWFE2F2QCLcBGAs/s1600/Eq_ES.png?ssl=1" target="_blank"><img border="0" data-original-height="199" src="https://i0.wp.com/2.bp.blogspot.com/-ea4IXJm-ltc/WXHcCE7SBNI/AAAAAAAAXss/_kfSoMCXvjs38ARVuXiuSE4-7YWFE2F2QCLcBGAs/s640/Eq_ES.png?resize=450%2C199&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>where ES is the effect size (in Cohen this is referred as d). In this equation, Ya is the mean of the measures for treatment A, and Yb is the mean for treatment B. The denominator is the pooled standard deviation, which is computed as follows:</p></div>
<div>
<div><a rel="nofollow" href="https://i2.wp.com/1.bp.blogspot.com/-l-KaUZn0v1Q/WXHcZakHeCI/AAAAAAAAXsw/vP9STONoXbAkw31d9N-HazEWHAi1nKo9ACLcBGAs/s1600/Eq_SDpooled.png?ssl=1" target="_blank"><img border="0" data-original-height="262" src="https://i2.wp.com/1.bp.blogspot.com/-l-KaUZn0v1Q/WXHcZakHeCI/AAAAAAAAXsw/vP9STONoXbAkw31d9N-HazEWHAi1nKo9ACLcBGAs/s640/Eq_SDpooled.png?resize=450%2C262&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p></div>
<div></div>
<div>
<div></div>
<p>where SD are the standard deviation for treatments B and A.</p>
<p>This is the main definition but then every software or functions tend to use indexes correlated to this but not identical. We will see each way of calculating the effect size case by case.</p>
<p>
<h3>One-Way ANOVA </h3>
</div>
<h4>Sample size</h4>
<div>For simple models the power calculating can be performed with the package pwr:
</div>
<div>
<pre><code> library(pwr)  <br></code></pre>
<p></div>
<div>In the previous post (<a rel="nofollow" href="http://r-video-tutorial.blogspot.co.uk/2017/06/linear-models-anova-glms-and-mixed.html" target="_blank">Linear Models</a>) we worked on a dataset where we tested the impact on yield of 6 levels of nitrogen. Let’s assume that we need to run a similar experiment and we would like to know how many samples we should collect (or how many plants we should use in the glass house) for each level of nitrogen. To calculate this we need to do a power analysis.
<p>To compute the sample size required to reach good power we can run the following line of code:</p>
<pre><code> pwr.anova.test(k=6, f=0.25, sig.level=0.05, power=0.8)  <br></code></pre>
<p>Let’s start describing the options from the end. We have the option power, to specify the power you require for your experiment. In general, this can be set to 0.8, as mentioned above. The significance level is alpha and usually we are happy to accept a significance of 5%. Another option is k, which is the number of groups in our experiment, in this case we have 6 groups. Clearly if we were considering two treatments, the first with 6 levels and the second with 3, k would have been 6*3=18.<br>Finally we have the option f, which is the effect size. As I mentioned above, there are many indexes to express the effect size and f is one of them.<br>According to Cohen, f can be expressed as:</p>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-cHT4BKBbSV4/WXCMYZmRVcI/AAAAAAAAXqo/-SL6McHC0t8H58IYKj-aia9oUx_T3ap6wCLcBGAs/s1600/Eq1.png?ssl=1" target="_blank"><img border="0" data-original-height="166" src="https://i0.wp.com/3.bp.blogspot.com/-cHT4BKBbSV4/WXCMYZmRVcI/AAAAAAAAXqo/-SL6McHC0t8H58IYKj-aia9oUx_T3ap6wCLcBGAs/s640/Eq1.png?resize=450%2C166&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>where the numerator is the is the standard deviation of the effects that we want to test and the denominator is the common standard deviation. For two means, as in the equation we have seen above, f is simply equal to:</p>
<div><a rel="nofollow" href="https://i2.wp.com/4.bp.blogspot.com/-W3QEQvOYyW8/WXIV01cL9AI/AAAAAAAAXtg/M12LspGMcYsj7XzRUp_4TEk2m_KcczfJQCLcBGAs/s1600/F_from_d.png?ssl=1" target="_blank"><img border="0" data-original-height="196" src="https://i1.wp.com/4.bp.blogspot.com/-W3QEQvOYyW8/WXIV01cL9AI/AAAAAAAAXtg/M12LspGMcYsj7XzRUp_4TEk2m_KcczfJQCLcBGAs/s640/F_from_d.png?resize=450%2C196&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>Clearly, before running the experiment we do not really know what the effect size would be. In some case we may have an idea, for example from previous experiments or a pilot study. However, most of the times we do not have a clue. In such cases we can use the classification suggested by Cohen, who considered the following values for f:</p>
<div><a rel="nofollow" href="https://i0.wp.com/2.bp.blogspot.com/-uCryh34ArlE/WXCOjKrPOKI/AAAAAAAAXqw/87wh7GjgkDQ4AHNYE_itgKQKAjbYo52KgCLcBGAs/s1600/Table_f.png?ssl=1" target="_blank"><img border="0" data-original-height="362" src="https://i0.wp.com/2.bp.blogspot.com/-uCryh34ArlE/WXCOjKrPOKI/AAAAAAAAXqw/87wh7GjgkDQ4AHNYE_itgKQKAjbYo52KgCLcBGAs/s640/Table_f.png?resize=450%2C362&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>The general rule is that if we do not know anything about our experiment we should use a medium effect size, so in this case 0.25. This was suggested in the book Bausell &amp; Li and it is based on a review of 302 studies in the social and behavioral sciences. for this reason it may well be that the effect size of your experiment would be different. However, if you do not have any additional information this is the only thing the literature suggest.</p>
<p>The function above returns the following output:</p>
<pre><code> > pwr.anova.test(k=6, f=0.25, sig.level=0.05, power=0.8)  <br>    Balanced one-way analysis of variance power calculation   <br>        k = 6  <br>        n = 35.14095  <br>        f = 0.25  <br>    sig.level = 0.05  <br>      power = 0.8  <br> NOTE: n is number in each group  <br></code></pre>
<p>In this example we would need 36 samples for each nitrogen level to achieve a power of 80% with a significance of 5%.</p>
<p>
<h3>Power Calculation</h3>
<div>As I mentioned above, sometimes we have a dataset we collected assuming we could reach good power but we are not actually sure if that is the case. In those instances what we can do is the <i>a posteriori </i>power analysis, where we basically compute the power for a model we already fitted.</div>
<div></div>
<div>As you remember is the previous post about linear models, we fitted the following:
<pre><code> mod1 = aov(yield ~ nf, data=dat)  <br></code></pre>
<p></div>
<p>To compute the power we achieved here we first need to calculate the effect size. As discussed above we have several options: d, f and another index called partial eta squared.<br>Let’s start from d, which can be simply calculated using means and standard deviation of two groups, for example N0 (control) and N5:</p>
<pre><code> numerator = (mean(dat[dat$nf==&quot;N5&quot;,&quot;yield&quot;])-mean(dat[dat$nf==&quot;N0&quot;,&quot;yield&quot;]))  <br> denominator = sqrt((sd(dat[dat$nf==&quot;N5&quot;,&quot;yield&quot;])^2+sd(dat[dat$nf==&quot;N0&quot;,&quot;yield&quot;])^2)/2)  <br> d = numerator/denominator  <br></code></pre>
<p>This code simply computes the numerator (difference in means) and the denominator (pooled standard deviation) and then computes the Cohen’s d, which results in 0.38.</p>
<p>Again Cohen provides some values for the d, so that we can determine how large is our effects, which are presented below:</p>
<div><a rel="nofollow" href="https://i0.wp.com/3.bp.blogspot.com/-uBsuXl9jD_M/WXCS2cJma0I/AAAAAAAAXrE/Tpa1fjopgqsKTDMBEmBle9TEWSdopSsyACLcBGAs/s1600/Table_d.png?ssl=1" target="_blank"><img border="0" data-original-height="362" src="https://i2.wp.com/3.bp.blogspot.com/-uBsuXl9jD_M/WXCS2cJma0I/AAAAAAAAXrE/Tpa1fjopgqsKTDMBEmBle9TEWSdopSsyACLcBGAs/s640/Table_d.png?resize=450%2C362&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>From this table we can see that our effect size is actually low, and not medium as we assumed for the <i>a priori</i> analysis. This is important because if we run the experiment with 36 samples per group we may end up with unrealistic results simply due to low power. For this reason it is my opinion that we should always be a bit more conservative and maybe include some additional replicates or blocks, just to account for potential unforeseen differences between our assumptions and reality.</p>
<p>The function to compute power is again pwr.anova.test, in which the effect size is expressed as f. We have two ways of doing that, the first is by using the d values we just calculated and halve it, so in this case f = 0.38/2 = 0.19. However, this will tell you the specific effects size for the relation between N0 and N5, and not for the full set of treatments.</p>
<p>At this link there is an Excel file that you can use to convert between indexes of effect size:<br><a rel="nofollow" href="http://www.stat-help.com/spreadsheets/Converting%20effect%20sizes%202012-06-19.xls" target="_blank">http://www.stat-help.com/spreadsheets/Converting%20effect%20sizes%202012-06-19.xls</a></p>
<p>Another way to get a fuller picture is by using the partial Eta Squared, which can be calculated using the sum of squares:</p>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-2NUTJTDHDPE/WXCfvidC_wI/AAAAAAAAXrU/JlK0W-BwotcB_AV-16rMkHfbB_uNWWr9QCLcBGAs/s1600/EtaSquared.png?ssl=1" target="_blank"><img border="0" data-original-height="174" src="https://i0.wp.com/3.bp.blogspot.com/-2NUTJTDHDPE/WXCfvidC_wI/AAAAAAAAXrU/JlK0W-BwotcB_AV-16rMkHfbB_uNWWr9QCLcBGAs/s640/EtaSquared.png?resize=450%2C174&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>This will tell us the average effect size for all the treatments we applied, so not only for N5 compared to N0, but for all of them.<br>To compute the partial eta squared we first need to access the anova table, with the function anova:</p>
<pre><code> > anova(mod1)  <br> Analysis of Variance Table  <br> Response: yield  <br>       Df Sum Sq Mean Sq F value  Pr(>F)    <br> nf      5  23987 4797.4 12.396 6.075e-12 ***  <br> Residuals 3437 1330110  387.0             <br> ---  <br> Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1  <br></code></pre>
<p>From this table we can extract the sum of squares for the treatment (i.e. nf) and the sum of squares of the residuals and then solve the equation above:</p>
<pre><code> > EtaSQ = 23987/(23987+1330110)  <br> > print(EtaSQ)  <br> [1] 0.01771439  <br></code></pre>
<p>As for the other indexes, eta squares also has its table of interpretation:</p>
<div><a rel="nofollow" href="https://i2.wp.com/4.bp.blogspot.com/-JC1LFulshws/WXCixB_T1YI/AAAAAAAAXrk/TFZEdmT0vzUh_-ba2e2Zd3eNjGSB8wASACLcBGAs/s1600/Table_eta.png?ssl=1" target="_blank"><img border="0" data-original-height="381" src="https://i1.wp.com/4.bp.blogspot.com/-JC1LFulshws/WXCixB_T1YI/AAAAAAAAXrk/TFZEdmT0vzUh_-ba2e2Zd3eNjGSB8wASACLcBGAs/s640/Table_eta.png?resize=450%2C381&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>The relation between f and eta squared is the following:</p>
<div><a rel="nofollow" href="https://i2.wp.com/2.bp.blogspot.com/-oPlCg96Gdpw/WXChC1PuTcI/AAAAAAAAXrc/X4FDUu35_UgR37BYwlWIKiTlF3szve1dQCLcBGAs/s1600/f_from_eta.png?ssl=1" target="_blank"><img border="0" data-original-height="262" src="https://i2.wp.com/2.bp.blogspot.com/-oPlCg96Gdpw/WXChC1PuTcI/AAAAAAAAXrc/X4FDUu35_UgR37BYwlWIKiTlF3szve1dQCLcBGAs/s640/f_from_eta.png?resize=450%2C262&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>so to compute the f related to the full treatment we can simply do the following:</p>
<pre><code> > f = sqrt(EtaSQ / (1-EtaSQ))  <br> > print(f)  <br> [1] 0.1342902  <br></code></pre>
<p>So now we have everything we need to calculate the power of our model:</p>
<pre><code> > pwr.anova.test(k=6, n=571, f=f, sig.level=0.05)  <br>    Balanced one-way analysis of variance power calculation   <br>        k = 6  <br>        n = 571  <br>        f = 0.1342902  <br>    sig.level = 0.05  <br>      power = 1  <br> NOTE: n is number in each group  <br></code></pre>
<p>To compute the power we need to run again the function pwr.anova.test, but this time without specifying the option power, but replacing it with the option n, which is the number of samples per group.<br>As you remember from the previous post this was an unbalanced design, so the number of samples per group is not constant. We could either use a vector as input for n, with all the samples per each group. In that case the function will return a power for each group. However, what I did here is putting the lowest number, so that we are sure to reach good power for the lowest sample size.</p>
<p>As you can see even with the small effect size we are still able to reach a power of 1, meaning 100%. This is because the sample size is more than adequate to catch even such a small effect. You could try to run again the sample size calculation to actually see what would be the minimum sample requirement for the observed effect size.</p>
<p>
<h3>Linear Model</h3>
</div>
<div>The method we have seen above is only valid for one-way ANOVAs. For more complex model, which may simply be ANOVA with two treatments we should use the function specific for linear models.</div>
<div>
<h4>Sample Size</h4>
<p>To calculate the sample size for this analysis we can refer once again to the package pwr, but now use the function pwr.f2.test.<br>Using this function is slightly more complex because here we start reasoning in terms of degrees of freedom for the F ratio, which can be obtained using the following equation:</p>
<table cellspacing="0" align="center" cellpadding="0">
<tbody>
<tr>
<td><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-NLVKVsJWnWw/WXC9fIVCdSI/AAAAAAAAXr0/afcfFmgekEY9xOyFkuB8DK3P0Ac0gn5nACLcBGAs/s1600/FRatio.JPG?ssl=1" target="_blank"><img border="0" data-original-height="98" src="https://i2.wp.com/3.bp.blogspot.com/-NLVKVsJWnWw/WXC9fIVCdSI/AAAAAAAAXr0/afcfFmgekEY9xOyFkuB8DK3P0Ac0gn5nACLcBGAs/s1600/FRatio.JPG?resize=239%2C98&ssl=1" data-recalc-dims="1" data-original-width="239"></a></td>
</tr>
<tr>
<td>From: https://cnx.org/contents/crKQFJtQ@14/F-Distribution-and-One-Way-ANO</td>
</tr>
</tbody>
</table>
<p>where MS between is the mean square variance between groups and MS within is the mean square variance within each group.<br>These two terms have the following equations (again from: https://cnx.org/contents/crKQFJtQ@14/F-Distribution-and-One-Way-ANO) :</p>
<div><a rel="nofollow" href="https://i2.wp.com/3.bp.blogspot.com/-roZUTl62Cc4/WXC-AuCY0wI/AAAAAAAAXr4/YjFGPaWVwSURI4ox7GuZJTlBxPpRjtYTgCLcBGAs/s1600/MSbetween.JPG?ssl=1" target="_blank"><img border="0" data-original-height="72" src="https://i0.wp.com/3.bp.blogspot.com/-roZUTl62Cc4/WXC-AuCY0wI/AAAAAAAAXr4/YjFGPaWVwSURI4ox7GuZJTlBxPpRjtYTgCLcBGAs/s320/MSbetween.JPG?resize=443%2C72&ssl=1" data-recalc-dims="1" data-original-width="443"></a></div>
<div></div>
<div><a rel="nofollow" href="https://i1.wp.com/1.bp.blogspot.com/-kOvJvWue4Ig/WXC-EMhZ7GI/AAAAAAAAXr8/YF7FKPSFAREw3sf1OE7K_GckpFj_7vIEwCLcBGAs/s1600/MSwithin.JPG?ssl=1" target="_blank"><img border="0" data-original-height="74" src="https://i0.wp.com/1.bp.blogspot.com/-kOvJvWue4Ig/WXC-EMhZ7GI/AAAAAAAAXr8/YF7FKPSFAREw3sf1OE7K_GckpFj_7vIEwCLcBGAs/s320/MSwithin.JPG?resize=397%2C74&ssl=1" data-recalc-dims="1" data-original-width="397"></a></div>
<p>The degrees of freedom we need to consider are the denominators of the last two equations. For an <i>a priori</i> power analysis we need to input the option u, with the degrees of freedom of the numerator of the F ratio, thus MS between. As you can see this can be computed as k-1, for a one-way ANOVA.<br>For more complex model we need to calculate the degrees of freedom ourselves. This is not difficult because we can generate dummy datasets in R with the specific treatment structure we require, so that R will compute the degrees of freedom for us.<br>We can generate dummy dataset very easily with the function expand.grid:</p>
<pre><code> > data = expand.grid(rep=1:3, FC1=c(&quot;A&quot;,&quot;B&quot;,&quot;C&quot;), FC2=c(&quot;TR1&quot;,&quot;TR2&quot;))  <br> > data  <br>   rep FC1 FC2  <br> 1  1  A TR1  <br> 2  2  A TR1  <br> 3  3  A TR1  <br> 4  1  B TR1  <br> 5  2  B TR1  <br> 6  3  B TR1  <br> 7  1  C TR1  <br> 8  2  C TR1  <br> 9  3  C TR1  <br> 10  1  A TR2  <br> 11  2  A TR2  <br> 12  3  A TR2  <br> 13  1  B TR2  <br> 14  2  B TR2  <br> 15  3  B TR2  <br> 16  1  C TR2  <br> 17  2  C TR2  <br> 18  3  C TR2  <br></code></pre>
<p>Working with expand.grid is very simple. We just need to specify the level for each treatment and the number of replicates (or blocks) and the function will generate a dataset with every combination.<br>Now we just need to add the dependent variable, which we can generate randomly from a normal distribution:</p>
<pre><code> data$Y = rnorm(nrow(data))  <br></code></pre>
<p>Now our dataset is ready so we can fit a linear model to it and generate the ANOVA table:</p>
<pre><code> > mod.pilot = lm(Y ~ FC1*FC2, data=data)  <br> > anova(mod.pilot)  <br> Analysis of Variance Table  <br> Response: Y  <br>      Df Sum Sq Mean Sq F value Pr(>F)  <br> FC1    2 0.8627 0.4314 0.3586 0.7059  <br> FC2    1 3.3515 3.3515 2.7859 0.1210  <br> FC1:FC2  2 1.8915 0.9458 0.7862 0.4777  <br> Residuals 12 14.4359 1.2030  <br></code></pre>
<p>Since this is a dummy dataset all the sum of squares and the other values are meaningless. We are only interested in looking at the degrees of freedom.<br>To calculate the sample size for this analysis we can refer once again to the package pwr, but now use the function pwr.f2.test, as follows:</div>
<div></div>
<pre><code> pwr.f2.test(u = 2, f2 = 0.25, sig.level = 0.05, power=0.8)  <br></code></pre>
<div>The first option in the function is u, which represents the degrees of freedom of the numerator of the F ratio. This is related to the degrees of freedom of the component we want to focus on. As you probably noticed from the model, we are trying to see if there is an interaction between two treatments. From the ANOVA table above we can see that the degrees of freedom of the interaction are equal to 2, so that it what we include as u.<br>Other options are again power and significance level, which we already discussed. Moreover, in this function the effect size is f2, which is again different from the f we’ve seen before. F2 again has its own table:
<div><a rel="nofollow" href="https://i1.wp.com/3.bp.blogspot.com/-joShefTvFwQ/WXDABu4bdHI/AAAAAAAAXsI/3KLMXx8aCMYkXgDOfCJJPjwt-sQPtHH3gCLcBGAs/s1600/Table_f2.png?ssl=1" target="_blank"><img border="0" data-original-height="362" src="https://i0.wp.com/3.bp.blogspot.com/-joShefTvFwQ/WXDABu4bdHI/AAAAAAAAXsI/3KLMXx8aCMYkXgDOfCJJPjwt-sQPtHH3gCLcBGAs/s640/Table_f2.png?resize=450%2C362&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>Since we assume we have no idea about the real effect size we use a medium value for the <i>a priori</i> testing.</p>
<p>The function returns the following table:</p>
<pre><code> > pwr.f2.test(u = 2, f2 = 0.25, sig.level = 0.05, power=0.8)  <br>    Multiple regression power calculation   <br>        u = 2  <br>        v = 38.68562  <br>        f2 = 0.25  <br>    sig.level = 0.05  <br>      power = 0.8  <br></code></pre>
<p>As you can see what the function is actually providing us is the value of the degrees of freedom for the denominator of the F test (with v), which results in 38.68, so 39 since we always round it by excess.<br>If we look to the equation to compute MS withing we can see that the degrees of freedom is given by n-k, meaning that to transform the degrees of freedom into a sample size we need to add what we calculated before for the option u. The sample size is then equal to n = v + u + 1, so in this case the sample size is equal 39 + 2 + 1 = 42</p>
<p>This is not the number of samples per group but it is the <b>total number of samples</b>.</p>
<p>Another way of looking at the problem would be to compute the total power of our model, and not just how much power we have to discriminate between levels of one of the treatments (as we saw above). To do so we can still use the function pwr.f2.test, but with some differences. The first is that we need to compute u using all elements in the model, so basically sum the decrees of freedom of the ANOVA table, or sum all the coefficients in the model minus the intercept:</p>
<pre><code> u = length(coef(mod3))-1  <br></code></pre>
<p>Another difference is in how we compute the effects size f2. Before we used its relation with partial eta square, now we can use its relation with the R2 of the model:</p>
<div><a rel="nofollow" href="https://i2.wp.com/2.bp.blogspot.com/-HDc-G_uY7Ns/WXHfUE5Sy2I/AAAAAAAAXtA/6I2Lc8G0X4IUpmCZ1NRqN9sG4HE2dyZ1wCLcBGAs/s1600/Eq_f2_r2.png?ssl=1" target="_blank"><img border="0" data-original-height="189" src="https://i0.wp.com/2.bp.blogspot.com/-HDc-G_uY7Ns/WXHfUE5Sy2I/AAAAAAAAXtA/6I2Lc8G0X4IUpmCZ1NRqN9sG4HE2dyZ1wCLcBGAs/s640/Eq_f2_r2.png?resize=450%2C189&ssl=1" data-recalc-dims="1" data-original-width="450"></a></div>
<p>With these additional element we can compute the power of the model.</p>
<p>
<h4>Power Calculation</h4>
</div>
<div>Now we look at estimating the power for a model we’ve already fitted, which can be done with the same function.</div>
<div>We will work with one of the models we used in the post about <a rel="nofollow" href="http://r-video-tutorial.blogspot.co.uk/2017/06/linear-models-anova-glms-and-mixed.html" target="_blank">Linear Models</a>:
</div>
<div>
<pre><code> mod3 = lm(yield ~ nf + bv, data=dat)   <br></code></pre>
<p>Once again we first need to calculate the observed effect size as the eta squared, using again the sum of squares:</p>
<pre><code> > Anova(mod3, type=&quot;III&quot;)  <br> Anova Table (Type III tests)  <br> Response: yield  <br>       Sum Sq  Df F value  Pr(>F)    <br> (Intercept) 747872  1 2877.809 &lt; 2.2e-16 ***  <br> nf      24111  5  18.555 &lt; 2.2e-16 ***  <br> bv     437177  1 1682.256 &lt; 2.2e-16 ***  <br> Residuals  892933 3436              <br> ---  <br> Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1  <br></code></pre>
<p>In this example, I used the function Anova (with option type=”III”) in the package car just to remind you that if you have an unbalanced design, like in this case, you should use the type III sum of squares.<br>From this table we can obtain the sum of squares we need to compute the eta squared, for example for nf we will use the following code:</p>
<pre><code> > EtaSQ = 24111/(24111+892933)  <br> > EtaSQ  <br> [1] 0.02629209  <br></code></pre>
<p>Then we need to transform this into f2 (of f squared), which is what the pwr.f2.test function uses:</p>
<pre><code> > f2 = EtaSQ / (1-EtaSQ)  <br> > f2  <br> [1] 0.02700203  <br></code></pre>
<p>The only thing we need to do now is calculating the value of v, i.e. the denominator degrees of freedom. This is equal to the n (number of samples) – u – 1, but a quick way of obtaining this number is looking at the anova table above and take the degrees of freedom of the residuals, i.e. 3436.</p>
<p>Now we have everything we need to obtain the observed power:</p>
<pre><code> > pwr.f2.test(u = 5, v = 3436, f2 = f2, sig.level = 0.05)  <br>    Multiple regression power calculation   <br>        u = 5  <br>        v = 3436  <br>        f2 = 0.02700203  <br>    sig.level = 0.05  <br>      power = 1  <br></code></pre>
<p>which again returns a very high power, since we have a lot of samples.</p>
<h3>Generalized Linear Models</h3>
<div>For GLM we need to install the package lmsupport:</div>
<div></div>
<pre><code> #install.packages(&quot;lmSupport&quot;)  <br> library(lmSupport)  <br></code></pre>
<p>
<h4>Sample Size</h4>
<p>For calculating the sample size for GLM we can use the same procedure we used for linear models.</p>
<p>
<h4>Power Calculation</h4>
<div>For this example we are going to use one of the model we discussed in the post about <a rel="nofollow" href="http://r-video-tutorial.blogspot.co.uk/2017/07/generalized-linear-models-and-mixed.html" target="_blank">GLM</a>, using the dataset beall.webworms (n = 1300):</div>
<div></div>
<pre><code> dat = beall.webworms  <br> pois.mod2 = glm(y ~ block + spray*lead, data=dat, family=c(&quot;poisson&quot;))   <br></code></pre>
<p>Once again we would need to compute effect size and degrees of freedom. As before, we can use the function anova to generate the data we need:</p>
<pre><code> > anova(pois.mod2)  <br> Analysis of Deviance Table  <br> Model: poisson, link: log  <br> Response: y  <br> Terms added sequentially (first to last)  <br>       Df Deviance Resid. Df Resid. Dev  <br> NULL            1299   1955.9  <br> block   12 122.040   1287   1833.8  <br> spray    1 188.707   1286   1645.2  <br> lead    1  42.294   1285   1602.8  <br> spray:lead 1  4.452   1284   1598.4  <br></code></pre>
<p>Let’s say we are interested in looking at the interaction between spray and lead, its degrees of freedom are 1, so this is our u. On its side we also have the residuals degrees of freedom, so v is 1284.<br>The other thing we need is the effect size, which we can compute with the function modelEffectSizes from the package lmSupport:</p>
<pre><code> > modelEffectSizes(pois.mod2)  <br> glm(formula = y ~ block + spray * lead, family = c(&quot;poisson&quot;),   <br>   data = dat)  <br> Coefficients  <br>       SSR df pEta-sqr dR-sqr  <br> block 122.0402 12  0.0709   NA  <br> spray 142.3487 1  0.0818 0.0849  <br> lead  43.7211 1  0.0266 0.0261  <br> Sum of squared errors (SSE): 1598.4  <br> Sum of squared total (SST): 1675.9  <br></code></pre>
<p>This function calculates the partial eta squares, and it works also for lm models. As you can see it does not provide the eta squared for the interaction, but just to be on the safe side we can use the lowest value (0.03) from the values provided for sparay and lead.<br>Now that we have the observed eta squared we can use the function modelPower:</p>
<pre><code>> modelPower(u=1, v=1284, alpha=0.05, peta2=0.03)<br>Results from Power Analysis<br><br>pEta2 = 0.030<br>u =     1 <br>v =     1284.0 <br>alpha = 0.050 <br>power = 1.000 <br></code></pre>
<p>This function can take the option f2, as we’ve seen before for the package pwr. However, since computing the partial eta square is generally easier, we can use the option peta2 and use directly this index.<br>Once again our power is very high.</p>
<p>
<h3>Linear Mixed Effects Models</h3>
<div>For power analysis with mixed effects models we would need to install the following packages:
</div>
<div>
<pre><code> #install.packages(&quot;simr&quot;)  <br> library(simr)  <br></code></pre>
<p>In this example we will be working with models fitted with the package lme4, but what is discussed here should work also with models fitted with nlme.</p>
<h4>Sample Size</h4>
</div>
<div><i>A priori </i>power analysis for mixed effect model is not easy. There are packages that should provide functions to do that (e.g. simstudy and longpower), but they are probably more related to the medical sciences and I found them difficult to use. For this reason I decided that probably the easiest way to test the power of an experiment for which we need to use a mixed-effect model (e.g. involving clustering or repeated measures) would be to use a dummy dataset again and simulation. However, please be advised that I am not 100% sure of the validity of this procedure.</div>
<div></div>
<div>To create the dummy dataset we can use the same procedure we employed above, with expand.grid:</div>
<div></div>
<pre><code> data = expand.grid(subject=1:5, treatment=c(&quot;Tr1&quot;, &quot;Tr2&quot;, &quot;Tr3&quot;))  <br> data$Y = numeric(nrow(data))  <br></code></pre>
<div></div>
<div>In this case we are simulating a simple experiment with 5 subjects, 3 treatments and a within subject design, like a crossover I suppose.<br>As you can see the Y has not been drawn from a normal distribution, this is because for the time being it is just a list of zeroes. We need to create data for each treatment as follows:
<pre><code> data[data$treatment==&quot;Tr1&quot;,&quot;Y&quot;] = rnorm(nrow(data[data$treatment==&quot;Tr1&quot;,]), mean=20, sd=1)  <br> data[data$treatment==&quot;Tr2&quot;,&quot;Y&quot;] = rnorm(nrow(data[data$treatment==&quot;Tr2&quot;,]), mean=20.5, sd=1)  <br> data[data$treatment==&quot;Tr3&quot;,&quot;Y&quot;] = rnorm(nrow(data[data$treatment==&quot;Tr3&quot;,]), mean=21, sd=1)  <br></code></pre>
<p></div>
<div>In these lines I created three samples, from normal distribution which means differ by half their standard deviation. This should provide an effect size (d) of around 0.5, so medium.
<p>Now we can create the model:</p>
</div>
<pre><code> mod1 = lmer(Y ~ treatment + (1|subject), data=data)  <br> summary(mod1)  <br></code></pre>
<div>and then test its power with the function powerSim from the package simr. This function runs 1000 simulation and provide a measure for the power of the experiment:
<pre><code> > powerSim(mod1, alpha=0.05)  <br> Power for predictor 'treatment', (95% confidence interval):  <br>    25.90% (23.21, 28.73)  <br> Test: Likelihood ratio  <br> Based on 1000 simulations, (84 warnings, 0 errors)  <br> alpha = 0.05, nrow = 15  <br> Time elapsed: 0 h 3 m 2 s  <br> nb: result might be an observed power calculation  <br> Warning message:  <br> In observedPowerWarning(sim) :  <br>  This appears to be an &quot;observed power&quot; calculation  <br></code></pre>
<p></div>
<p>From this output we can see that our power is very low, so we probably need to increase the number of subjects and then try again the simulation.</p>
<p>Let’s now look at repeated measures. In this case we do not only have the effect size to account for in the data, but also the correlation between in time between measures.</p>
<pre><code> library(mvtnorm)  <br>   <br> sigma &lt;- matrix(c(1, 0.5, 0.5, 0.5,   <br>          0.5, 1, 0.5, 0.5,  <br>          0.5, 0.5, 1, 0.5,  <br>                0.5, 0.5, 0.5 ,1 ), ncol=4, byrow=T)  <br>   <br>   <br> data = expand.grid(subject=1:4, treatment=c(&quot;Tr1&quot;, &quot;Tr2&quot;, &quot;Tr3&quot;), time=c(&quot;t1&quot;,&quot;t2&quot;,&quot;t3&quot;,&quot;t4&quot;))  <br> data$Y = numeric(nrow(data))  <br>   <br> T1 = rmvnorm(4, mean=rep(20, 4), sigma=sigma)  <br> T2 = rmvnorm(4, mean=rep(20.5, 4), sigma=sigma)  <br> T3 = rmvnorm(4, mean=rep(21, 4), sigma=sigma)  <br>   <br> data[data$subject==1&amp;data$treatment==&quot;Tr1&quot;,&quot;Y&quot;] = T1[1,]  <br> data[data$subject==2&amp;data$treatment==&quot;Tr1&quot;,&quot;Y&quot;] = T1[2,]  <br> data[data$subject==3&amp;data$treatment==&quot;Tr1&quot;,&quot;Y&quot;] = T1[3,]  <br> data[data$subject==4&amp;data$treatment==&quot;Tr1&quot;,&quot;Y&quot;] = T1[4,]  <br>   <br> data[data$subject==1&amp;data$treatment==&quot;Tr2&quot;,&quot;Y&quot;] = T2[1,]  <br> data[data$subject==2&amp;data$treatment==&quot;Tr2&quot;,&quot;Y&quot;] = T2[2,]  <br> data[data$subject==3&amp;data$treatment==&quot;Tr2&quot;,&quot;Y&quot;] = T2[3,]  <br> data[data$subject==4&amp;data$treatment==&quot;Tr2&quot;,&quot;Y&quot;] = T2[4,]  <br>   <br> data[data$subject==1&amp;data$treatment==&quot;Tr3&quot;,&quot;Y&quot;] = T3[1,]  <br> data[data$subject==2&amp;data$treatment==&quot;Tr3&quot;,&quot;Y&quot;] = T3[2,]  <br> data[data$subject==3&amp;data$treatment==&quot;Tr3&quot;,&quot;Y&quot;] = T3[3,]  <br> data[data$subject==4&amp;data$treatment==&quot;Tr3&quot;,&quot;Y&quot;] = T3[4,]  <br>   <br>   <br> modRM = lmer(Y ~ treatment + (time|subject), data=data)  <br> summary(modRM)  <br>   <br> powerSim(modRM, alpha=0.05)  <br></code></pre>
<p>In this case we need to use the function rmvnorm to draw, from a normal distribution, samples with a certain correlation. For this example I followed the approach suggested by <a rel="nofollow" href="https://twitter.com/williamahuber?lang=en" target="_blank">William Huber</a> here: <a rel="nofollow" href="https://stats.stackexchange.com/questions/24257/how-to-simulate-multivariate-outcomes-in-r/24271#24271" target="_blank">https://stats.stackexchange.com/questions/24257/how-to-simulate-multivariate-outcomes-in-r/24271#24271</a></p>
<p>Basically, if we assume a correlation equal to 0.5 between time samples (which is what the software <a rel="nofollow" href="http://www.gpower.hhu.de/en.html" target="_blank">G*Power</a> does for repeated measures), we first need to create a symmetrical matrix in sigma. This will allow rmvnorm to produce values from distributions with standard deviation equal to 1 and 0.5 correlation.<br>A more elegant approach is the one suggested by Ben Amsel on his blog: <a rel="nofollow" href="https://cognitivedatascientist.com/2015/12/14/power-simulation-in-r-the-repeated-measures-anova-5/" target="_blank">https://cognitivedatascientist.com/2015/12/14/power-simulation-in-r-the-repeated-measures-anova-5/</a></p>
<pre><code> sigma = 1 # population standard deviation  <br> rho = 0.5 #Correlation between repeated measurs  <br> # create k x k matrix populated with sigma  <br> sigma.mat &lt;- rep(sigma, 4)  <br> S &lt;- matrix(sigma.mat, ncol=length(sigma.mat), nrow=length(sigma.mat))  <br> # compute covariance between measures  <br> Sigma &lt;- t(S) * S * rho   <br> # put the variances on the diagonal   <br> diag(Sigma) &lt;- sigma^2   <br></code></pre>
<p>The result is the same but at least here you can specify different values for SD and correlation.</p>
<p>The other elementS the function needs are mean values, for which I used the same as before. This should guarantee a difference of around half a standard deviation between treatments.<br>The remaining of the procedure is the same we used before with no changes.</p>
<p>As I said before, I am not sure if this is the correct way of computing power for linear mixed effects models. It may be completely or partially wrong, and if you know how to do this or you have comments please do not hesitate to write them below.</p>
<p>
<h3>Power Analysis</h3>
<p>As we have seen with the <i>a priori</i> analysis, computing the power of mixed effects models is actually very easy with the function powerSim.</p>
<p>
<h3>References</h3>
<p>PWR package Vignette: <a rel="nofollow" href="https://cran.r-project.org/web/packages/pwr/vignettes/pwr-vignette.html" target="_blank">https://cran.r-project.org/web/packages/pwr/vignettes/pwr-vignette.html</a></p>
<p>William E. Berndtson (1991). “A simple, rapid and reliable method for selecting or assessing the number of replicates for animal experiments”<br><a rel="nofollow" href="http://scholars.unh.edu/cgi/viewcontent.cgi?article=1312&context=nhaes" target="_blank">http://scholars.unh.edu/cgi/viewcontent.cgi?article=1312&amp;context=nhaes</a></p>
<p><b>NOTE</b>:<br><i>This paper is what some of my colleagues, who deal with animal experiments, use to calculate how many subjects to use for their experiments. I’m not sure if this is still a good method of computing sample size, but I just felt I should include it as additional reading.</i><br><i><br></i><b>NOTE 2:</b><br><i>The article above computes the number of replicates based on the estimated difference between means and coefficient of variation (CV) </i><i>for each group. Since a lot of researchers always talk about CV, I thought of saying that the power analysis actually does not seem to care about CV. This is because one of the assumptions of linear models is that the variance between groups would be constant, if this does not happen theoretically we should not even try an ANOVA. </i><br><i><br></i></p>
<p>Berkowitz J. “Sample Size Estimation” – <a rel="nofollow" href="http://www.columbia.edu/~mvp19/RMC/M6/M6.doc" target="_blank">http://www.columbia.edu/~mvp19/RMC/M6/M6.doc</a></p>
<p>This document gives you some rule of thumb to determine the sample size for a number of experiments.</p>
</div>
<div></div>
	<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="http://r-video-tutorial.blogspot.com/2017/07/power-analysis-and-sample-size.html"> R tutorial for Spatial Statistics</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a rel="nofollow" href="https://www.r-project.org/" title="The R Project for Statistical Computing">R</a> news and <a rel="nofollow" href="https://www.r-bloggers.com/search/tutorial" title="R tutorials">tutorials</a> on topics such as: <a rel="nofollow" href="https://www.r-bloggers.com/search/data%20science" title="Data science">Data science</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data" title="Big Data">Big Data, <a rel="nofollow" href="https://www.r-users.com/" title="R jobs">R jobs</a>, visualization (<a rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2" title="ggplot and ggplot2 tutorials">ggplot2</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/boxplot" title="Boxplots using lattice and ggplot2 tutorials">Boxplots</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/map" title="Maps and gis">maps</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/animation" title="Animation in R">animation</a>), programming (<a rel="nofollow" href="https://www.r-bloggers.com/search/RStudio" title="RStudio IDE for R">RStudio</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/sweave" title="Sweave and literate programming">Sweave</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX" title="LaTeX in R">LaTeX</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/SQL" title="SQL and databases">SQL</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/eclipse" title="Eclipse IDE for R">Eclipse</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/git" title="git and github, Version Control System">git</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/hadoop" title="Large data in R using Hadoop">hadoop</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping" title="Web Scraping of google, facebook, yahoo, twitter and more using R">Web Scraping</a>) statistics (<a rel="nofollow" href="https://www.r-bloggers.com/search/regression" title="Regressions and ANOVA analysis tutorials">regression</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/PCA" title="principal component analysis tutorial">PCA</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/time+series" title="Time series">time series</a>, <a rel="nofollow" href="https://www.r-bloggers.com/search/trading" title="finance trading">trading</a>) and more...
<img alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/4rvGopOrtmU" height="1"></a></div>