R for Teaching: Visualize a z-test

I occasionally write functions in R to help me with some aspect of teaching, usually teaching undergrad stats. I always intend to share them with others, but I don’t actually know many other people who use R for teaching. So why not share in blog posts? I’ll start now.

Disclaimer: This functions is untested by anyone but me, it might not work, and I provide no guarantee of accuracy. I mean, I try, but you know…

An R function for visualizing single-sample z-tests, a function I named zvis, produces graphs as below, using (usually) pretty simple options:

zvis(x=104, mu0=100, sigma=15, n=30)

I won’t paste the code here because it’s kind of long, but anyone interested can have it from this link –> zvis. The whole set of arguments can be seen after the break. If, by chance, anyone is interested in this function and wants more explanation of these options, or has suggestions for improving the function, please let me know.

The important options (with defaults, if present):
x                     The observed sample mean value
mu0=0                 Null hypothesis-implied population mean
sigma=1               Standard deviation of raw scores
n                     Sample size
tails = "twotailed"   Can also be "lower" or "upper" 
alpha=.05             Set to anything you like
xaxis=TRUE            Show X-axis values in raw score units?
zaxis=TRUE            Show X-axis values in z-score units?
zcrit=TRUE            Show value of z-critical?
zobs=TRUE             Show value of z-observed?
pval=TRUE             Show p-value on plot?
printalpha=TRUE       Show alpha value on plot?

Colors for various plot elements can be tweaked if necessary:
fillobs2 = "#0000FFAA"
borderobs2 = "navy"

It’s fairly flexible, but it’s set up to show graphs the way I personally draw them on the board. It could easily be turned into a shiny widget, but I only have shared hosting (webfaction; I recommend!) and have not yet been able to get shiny (or R-studio server) working anywhere but on my PC. I hope this helps someone, if only by showing them how not to write R functions 🙂


One thought on “R for Teaching: Visualize a z-test”

Leave a Reply

Your email address will not be published. Required fields are marked *