### Run Confidence Interval Example Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates confidence intervals. No specific setup required. ```R ci.examp() ``` -------------------------------- ### Demonstrate Confidence Interval Examples Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Runs examples for confidence interval plotting. Use when interactive R sessions are available. ```R ci.examp() if(interactive()) { run.ci.examp() } # 1 sided confidence intervals ci.examp(lower.conf=0, upper.conf=0.95) # non-symmetric intervals ci.examp(lower.conf=0.02, upper.conf=0.97) ``` -------------------------------- ### Run Old Version of Power Example Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Executes an older version of the power demonstration function. This function does not return any meaningful value. ```R run.power.examp.old() ``` -------------------------------- ### Run Central Limit Theorem Example Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates the Central Limit Theorem. Can be run with default parameters or by specifying the number of samples. ```R clt.examp() ``` ```R clt.examp(5) ``` -------------------------------- ### Illustrative Test Example Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html This example demonstrates the usage of a custom test function, likely for illustrative purposes rather than actual decision-making. ```R SnowsCorrectlySizedButOtherwiseUselessTestOfAnything(log(rnorm(100))) ``` -------------------------------- ### Run Power Example Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates statistical power concepts. Can be run with default parameters or by specifying sample size (n) or significance level (alpha). ```R power.examp() ``` ```R power.examp(n=25) ``` ```R power.examp(alpha=0.1) ``` -------------------------------- ### Interactive Correlation Examples Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Functions to demonstrate correlations with interactive Tk slider windows for adjusting correlation and R^2 values. ```APIDOC ## run.cor.examp ### Description Creates a scatterplot and an interactive Tk slider window to adjust the correlation. ### Usage ```R run.cor.examp(n = 100, seed, vscale = 1.5, hscale = 1.5, wait = FALSE) ``` ### Arguments * `n`: Number of points to plot. * `seed`: Seed for random number generation. * `vscale`: Vertical scale for `tkrplot`. * `hscale`: Horizontal scale for `tkrplot`. * `wait`: If TRUE, R waits for the Tk window to close. ### Details Allows interactive adjustment of the correlation coefficient via a Tk slider. The plot and sliders are in a single Tk window. ## run.cor2.examp ### Description Creates a scatterplot and interactive Tk slider windows to adjust both correlation and R^2. ### Usage ```R run.cor2.examp(n = 100, seed, vscale = 1.5, hscale = 1.5, wait = FALSE) ``` ### Arguments * `n`: Number of points to plot. * `seed`: Seed for random number generation. * `vscale`: Vertical scale for `tkrplot`. * `hscale`: Horizontal scale for `tkrplot`. * `wait`: If TRUE, R waits for the Tk window to close. ### Details Provides sliders for both correlation and R^2, with updates synchronizing between them. The plot and sliders are in a single Tk window. ## run.old.cor.examp ### Description Creates a scatterplot with a separate Tk slider window for correlation (uses default graphics). ### Usage ```R run.old.cor.examp(n = 100, seed) ``` ### Arguments * `n`: Number of points to plot. * `seed`: Seed for random number generation. ### Details Uses the default R graphics device and a separate window for the correlation slider. ## run.old.cor2.examp ### Description Creates a scatterplot with separate Tk slider windows for correlation and R^2 (uses default graphics). ### Usage ```R run.old.cor2.examp(n = 100, seed) ``` ### Arguments * `n`: Number of points to plot. * `seed`: Seed for random number generation. ### Details Uses the default R graphics device and separate windows for the correlation and R^2 sliders. ``` -------------------------------- ### Box-Cox Transform Example Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates the Box-Cox transform function 'bct' by applying it with different lambda values and visualizing the results with QQ-norm plots and a histogram. ```R y <- rlnorm(500, 3, 2) par(mfrow=c(2,2)) qqnorm(y) qqnorm(bct(y,1/2)) qqnorm(bct(y,0)) hist(bct(y,0)) ``` -------------------------------- ### Visual Hypothesis Testing Setup Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Functions to set up visual hypothesis tests where users identify the graph that does not belong. Requires specifying a function `FUN` to generate plots. ```R vis.test(..., FUN, nrow=3, ncol=3, npage=3, data.name = "", alternative) ``` ```R vt.qqnorm(x, orig=TRUE) ``` ```R vt.normhist(x, ..., orig=TRUE) ``` ```R vt.scatterpermute(x, y, ..., orig=TRUE) ``` ```R vt.tspermute(x, type='l', ..., orig=TRUE) ``` ```R vt.residpermute(model, ..., orig=TRUE) ``` ```R vt.residsim(model, ..., orig=TRUE) ``` -------------------------------- ### Demonstrate Central Limit Theorem Examples Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Plots histograms of sample means from various distributions to demonstrate the Central Limit Theorem. Run with different 'n' values to observe the convergence to normality. ```R clt.examp() clt.examp(5) clt.examp(30) clt.examp(50) ``` -------------------------------- ### Start Markdown transcript logging Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Initializes a transcript log for commands and results in Markdown format. Plots are saved as PNG files. Use `mdtxtStop()` to end logging. ```R mdtxtStart(dir=tempfile('mdtxt'), file='transcript.md', commands=TRUE, results=TRUE, append=FALSE, cmdfile, visible.only=TRUE) ``` -------------------------------- ### Plotting Coin Faces with rgl Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates plotting coin faces using the rgl package. The 'Not run' tag indicates this example is not automatically executed. ```R ## Not run: plot.rgl.coin(heads=coin.faces$H, tails=coin.faces$T) ## End(Not run) ``` -------------------------------- ### Data Simulation using Named Parameters Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html This example shows how to use named parameters and index by names within the simulation expression. It includes defining named vectors for parameters like 'h' and 'sig'. ```R myexpr <- quote({ n <- length(sex) height <- h[ as.character(sex)] + rnorm(n,0,sig) }) simheight <- simfun(eval(myexpr), drop=c('n','h','sig'), h=c(Male=69,Female=64), sig=3) my.df <- data.frame(sex=factor(sample(c('Male','Female'),100, replace=TRUE))) (simdat <- simheight(my.df, seed='example')) ``` -------------------------------- ### Start text transcript logging Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Initializes a transcript log for commands and/or results to a text file. Use `txtStop()` to end logging. The `append` argument controls whether to overwrite or add to an existing file. ```R txtStart(file, commands=TRUE, results=TRUE, append=FALSE, cmdfile, visible.only=TRUE) ``` -------------------------------- ### Start Enhanced Text Transcript Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Starts recording an R session to an enhanced text file. Use this to create transcripts that can be post-processed with enscript for PostScript output, including graphics. ```R etxtStart() ``` -------------------------------- ### Plot Monthly Calendar Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Generates a calendar for a specified month and year. This example shows how to create a calendar for 'May' of the current year. ```R cal('May') ``` -------------------------------- ### Start Word transcript logging Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Initializes a transcript log for commands and results, formatted for Microsoft Word with specified font size. Use `wdtxtStop()` to end logging. ```R wdtxtStart(commands=TRUE, results=TRUE, fontsize=9, cmdfile, visible.only=TRUE) ``` -------------------------------- ### Open GnuPlot Connection Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Establishes a pipe connection to a GnuPlot process. Requires GnuPlot to be installed. Use to prepare for sending plotting commands. ```R gp.open(where='c:/progra~1/GnuPlot/bin/pgnuplot.exe') ``` -------------------------------- ### Simulate Mixed Effects Model with Explicit Parameters Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html This example simulates data from a mixed-effects model where the parameters for the number of states, cities, and error variances are explicitly provided in a list. ```R simheight <- simfun({ state <- gl(n.state, n/n.state) city <- gl(n.city*n.state, n/n.city/n.state) sex <- gl(2, n.city, length=n, labels=c('F','M') ) height <- h[sex] + rnorm(n.state,0,sig.state)[state] + rnorm(n.city*n.state,0,sig.city)[city] + rnorm(n,0,sig.e) }, drop=c('n.state','n.city','n','sig.city','sig.state','sig.e','h')) heightdat <- simheight( list( n.state=5, n.city=2, n=100, sig.state=10, sig.city=3, sig.e=1, h=c(64,69) )) ``` -------------------------------- ### Run System Commands for File Conversion Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Executes external commands to convert files using enscript/ps2pdf or pandoc. Assumes these utilities are installed and in the system's PATH. ```R system(paste('enscript -e -B -p transcript.ps ', my.file) ) system('ps2pdf transcript.ps') ``` ```R system(paste('pandoc -o transcript.docx ', my.file)) ``` -------------------------------- ### Generate Chernoff Faces Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates basic usage of the faces() function with different data inputs, including matrices and data frames. Includes an interactive example using tkexamp for real-time face manipulation. ```R faces(rbind(1:3,5:3,3:5,5:7)) ``` ```R data(longley) faces(longley[1:9,]) ``` ```R set.seed(17) faces(matrix(sample(1:1000,128,),16,8),main="random faces") ``` ```R if(interactive()){ tke1 <- rep( list(list('slider',from=0,to=1,init=0.5,resolution=0.1)), 15) names(tke1) <- c('FaceHeight','FaceWidth','FaceShape','MouthHeight', 'MouthWidth','SmileCurve','EyesHeight','EyesWidth','HairHeight', 'HairWidth','HairStyle','NoseHeight','NoseWidth','EarWidth','EarHeight') tkfun1 <- function(...){ tmpmat <- rbind(Min=0,Adjust=unlist(list(...)),Max=1) faces(tmpmat, scale=FALSE) } tkexamp( tkfun1, list(tke1), plotloc='left', hscale=2, vscale=2 ) } ``` -------------------------------- ### Start enhanced text transcript logging Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Initializes an enhanced transcript log with customizable colors for commands and results. Plots can be saved to EPS files. Use `etxtStop()` to end logging. ```R etxtStart(dir = tempfile("etxt"), file = "transcript.txt", commands = TRUE, results = TRUE, append = FALSE, cmdbg = "white", cmdcol = "red", resbg = "white", rescol = "navy", combg = "cyan", comcol = "black", cmdfile, visible.only = TRUE) ``` -------------------------------- ### Coordinate Conversion Examples with cnvrt.coords Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates various uses of the cnvrt.coords function for converting between different coordinate systems (usr, plt, fig, dev, tdev). Useful for precise placement of plot elements and linking elements across multiple plots. ```R old.par <- par(no.readonly=TRUE) par(mfrow=c(2,2),xpd=NA) # generate some sample data tmp.x <- rnorm(25, 10, 2) tmp.y <- rnorm(25, 50, 10) tmp.z <- rnorm(25, 0, 1) plot( tmp.x, tmp.y) # draw a diagonal line across the plot area tmp1 <- cnvrt.coords( c(0,1), c(0,1), input='plt' ) lines(tmp1$usr, col='blue') # draw a diagonal line accross figure region tmp2 <- cnvrt.coords( c(0,1), c(1,0), input='fig') lines(tmp2$usr, col='red') # save coordinate of point 1 and y value near top of plot for future plots tmp.point1 <- cnvrt.coords(tmp.x[1], tmp.y[1]) tmp.range1 <- cnvrt.coords(NA, 0.98, input='plt') # make a second plot and draw a line linking point 1 in each plot plot(tmp.y, tmp.z) tmp.point2 <- cnvrt.coords( tmp.point1$dev, input='dev' ) arrows( tmp.y[1], tmp.z[1], tmp.point2$usr$x, tmp.point2$usr$y, col='green') # draw another plot and add rectangle showing same range in 2 plots plot(tmp.x, tmp.z) tmp.range2 <- cnvrt.coords(NA, 0.02, input='plt') tmp.range3 <- cnvrt.coords(NA, tmp.range1$dev$y, input='dev') rect( 9, tmp.range2$usr$y, 11, tmp.range3$usr$y, border='yellow') # put a label just to the right of the plot and # near the top of the figure region. text( cnvrt.coords(1.05, NA, input='plt')$usr$x, cnvrt.coords(NA, 0.75, input='fig')$usr$y, "Label", adj=0) par(mfrow=c(1,1)) ``` ```R ## create a subplot within another plot (see also subplot) plot(1:10, 1:10) tmp <- cnvrt.coords( c( 1, 4, 6, 9), c(6, 9, 1, 4) ) par(plt = c(tmp$dev$x[1:2], tmp$dev$y[1:2]), new=TRUE) hist(rnorm(100)) par(fig = c(tmp$dev$x[3:4], tmp$dev$y[3:4]), new=TRUE) hist(rnorm(100)) par(old.par) ``` -------------------------------- ### Dependent Sliders Example Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html This snippet is intended to demonstrate dependent sliders, where adjusting one slider automatically updates another to maintain a specific relationship (e.g., p + q = 1). The actual code for this example is not provided in the source. ```R # example 3, dependent sliders ## Not run: ``` -------------------------------- ### Demonstrate Regression Trees Interactively Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Interactively demonstrates regression trees by recursively partitioning a dataset. Requires an interactive session and the 'ethanol' dataset. ```R if(interactive()){ data('ethanol', package='lattice') print(with(ethanol, tree.demo(E,NOx))) } ``` -------------------------------- ### Plot Symbols from Function Data Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Plots symbols using a function that returns a matrix. The `ms.polygram` function is used as an example. ```R plot(1:10, 1:10) my.symbols( 1:10, 1:10, ms.polygram, n=1:10, inches=0.3 ) ``` -------------------------------- ### Build Probability Distribution with TkBuildDist Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Interactively build a probability distribution by clicking on a plot. Use TkBuildDist for custom data ranges or TkBuildDist2 for a default range. Logspline fitting is optional and may slow performance on older machines. ```r TkBuildDist(x = seq(min + (max - min)/nbin/2, max - (max - min)/nbin/2, length.out = nbin), min = 0, max = 10, nbin = 10, logspline = TRUE, intervals = FALSE) ``` ```r TkBuildDist2( min=0, max=1, nbin=10, logspline=TRUE) ``` ```r if(interactive()){ tmp1 <- TkBuildDist() tmp2 <- TkBuildDist2() } ``` -------------------------------- ### Simulate with Fixed Population Data Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html This snippet demonstrates using simfun to simulate data based on a fixed dataset, extracting specific columns like Population, Income, and Illiteracy. ```R simstate <- simfun({ tmp <- state.df[as.character(State),] Population <- tmp[['Population']] Income <- tmp[['Income']] Illiteracy <- tmp[['Illiteracy']] }, state.df=as.data.frame(state.x77), drop=c('tmp','state.df')) simstate(data.frame(State=sample(state.name,10))) ``` -------------------------------- ### Plotting Predicted Values with Predict.Plot Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Generates plots of predicted values from 'lm' or 'glm' models against a specified predictor variable. Requires the 'splines' library for some examples. ```R library(splines) fit.lm1 <- lm( Sepal.Width ~ ns(Petal.Width,3)*ns(Petal.Length,3)+Species, data=iris) Predict.Plot(fit.lm1, pred.var = "Petal.Width", Petal.Width = 1.22, Petal.Length = 4.3, Species = "versicolor", plot.args = list(ylim=range(iris$Sepal.Width), col='blue'), type = "response") Predict.Plot(fit.lm1, pred.var = "Petal.Width", Petal.Width = 1.22, Petal.Length = 4.3, Species = "virginica", plot.args = list(col='red'), type = "response", add=TRUE) Predict.Plot(fit.lm1, pred.var = "Petal.Width", Petal.Width = 1.22, Petal.Length = 4.4, Species = "virginica", plot.args = list(col='purple'), type = "response", add=TRUE) fit.glm1 <- glm( Species=='virginica' ~ Sepal.Width+Sepal.Length, data=iris, family=binomial) Predict.Plot(fit.glm1, pred.var = "Sepal.Length", Sepal.Width = 1.99, Sepal.Length = 6.34, plot.args = list(ylim=c(0,1), col='blue'), type = "response") Predict.Plot(fit.glm1, pred.var = "Sepal.Length", Sepal.Width = 4.39, Sepal.Length = 6.34, plot.args = list(col='red'), type = "response", add=TRUE) ``` -------------------------------- ### Interactively Explore Lattice Plots Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates `xyplot` functionality by allowing interactive selection of conditioning sets. Useful for understanding how lattice graphics create panels. ```r if(interactive()){ require(stats) lattice.demo(quakes$long, quakes$lat, quakes$depth) } ``` -------------------------------- ### Load 'steps' dataset in R Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Loads the 'steps' dataset. Use str(steps) or plot(steps) for further exploration. ```r data(steps) ## maybe str(steps) ; plot(steps) ... ``` -------------------------------- ### Basic Coin and Die Animation with rgl Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Initializes a coin or die in an rgl window. Use flip.rgl.coin() or roll.rgl.die() to animate. ```R if(interactive()){ rgl.coin() flip.rgl.coin() flip.rgl.coin(1) flip.rgl.coin(2) rgl.clear() # two-headed coin rgl.coin(tails=coin.faces$qh) rgl.clear() # letters instead of pictures rgl.coin(heads=coin.faces$H, tails=coin.faces$T) # biased flip flip.rgl.coin( sample(2,1, prob=c(0.65, 0.35) ) ) rgl.clear() rgl.die() roll.rgl.die() roll.rgl.die(6) # biased roll roll.rgl.die( sample(6,1, prob=c(1,2,3,3,2,1) ) ) } ``` -------------------------------- ### Run Normal and Binomial P-value Simulations Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Interactively run simulations for normal and binomial distributions to observe p-value distributions. Uses GUI wrappers for parameter changes and simulation refresh. ```R if(interactive()) { run.Pvalue.norm.sim() run.Pvalue.binom.sim() } ``` -------------------------------- ### Set Day for Monthly Calendar Plotting Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates how to get a function to set the plotting area for a specific day within a monthly calendar, allowing for custom content to be added. ```R setday <- cal(11, 2011) setday(3) text(0.5,0.5, 'Some\nCentered\nText') setday(8) text(1,1,'Top Right',adj=c(1,1)) setday(18) text(0,0,'Bottom Left', adj=c(0,0) ) setday(21) tmp.x <- runif(25) tmp.y <- rnorm(25, tmp.x, .1) mrgn.x <- 0.04*diff(range(tmp.x)) mrgn.y <- 0.04*diff(range(tmp.y)) updateusr( 0:1, 0:1, range(tmp.x)+c(-1,1)*mrgn.x, range(tmp.y)+c(-1,1)*mrgn.y) points(tmp.x, tmp.y) setday(30) tmp <- hist(rnorm(100), plot=FALSE) updateusr( 0:1, 0:1, range(tmp$breaks), range(tmp$counts*1.1,0) ) lines(tmp) ``` -------------------------------- ### run.Pvalue.norm.sim and run.Pvalue.binom.sim Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html These functions are GUI wrappers for simulating p-values from normal or binomial distributions. They allow users to adjust parameters and observe the distribution of p-values, demonstrating concepts like power and the effects of unmet assumptions. ```APIDOC ## run.Pvalue.norm.sim() ### Description GUI wrapper to simulate p-values from a normal distribution. ### Usage ```R run.Pvalue.norm.sim() ``` ## run.Pvalue.binom.sim() ### Description GUI wrapper to simulate p-values from a binomial distribution. ### Usage ```R run.Pvalue.binom.sim() ``` ### Details These functions generate samples, compute p-values for significance tests, and plot the p-values. Using NA for sigma0 results in sample standard deviations being used. When simulation conditions match hypothesized values, p-value distributions are approximately uniform. Changing parameters demonstrates power and the effects of unmet assumptions. ### Value P-values are invisibly returned. ``` -------------------------------- ### Plot Chernoff Faces with faces2 Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Illustrates plotting Chernoff faces using the faces2 function with random data. Includes an interactive example for adjusting face features using tkexamp. ```R faces2(matrix( runif(18*10), nrow=10), main='Random Faces') ``` ```R if(interactive()){ tke2 <- rep( list(list('slider',from=0,to=1,init=0.5,resolution=0.1)), 18) names(tke2) <- c('CenterWidth','TopBottomWidth','FaceHeight','TopWidth', 'BottomWidth','NoseLength','MouthHeight','MouthCurve','MouthWidth', 'EyesHeight','EyesBetween','EyeAngle','EyeShape','EyeSize','EyeballPos', 'EyebrowHeight','EyebrowAngle','EyebrowWidth') tkfun2 <- function(...){ tmpmat <- rbind(Min=0,Adjust=unlist(list(...)),Max=1) faces2(tmpmat, scale='none') } tkexamp( tkfun2, list(tke2), plotloc='left', hscale=2, vscale=2 ) } ``` -------------------------------- ### Demonstrate PPV and NPV Calculation Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates calculating Positive Predictive Value (PPV) and Negative Predictive Value (NPV) using a virtual population approach, which is more intuitive than Bayes' rule. Useful for understanding how sensitivity, specificity, and prevalence affect these values. ```R for(i in seq(1,11,2)) { SensSpec.demo(sens=0.95, spec=0.99, prev=0.01, step=i) if( interactive() ) { readline("Press Enter to continue") } } ``` -------------------------------- ### Chernoff Faces Visualization Setup Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html This code is a function definition for creating Chernoff faces, which represent rows of a data matrix by faces. It includes arguments for controlling the plotting and scaling of features. ```R faces(xy, which.row, fill = FALSE, nrow, ncol, scale = TRUE, byrow = FALSE, main, labels) ``` -------------------------------- ### Interactive Correlation Demonstration Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates correlations by creating a scatterplot with a Tk slider window. Allows interactive adjustment of correlation and R^2 values. ```R if(interactive()) { run.cor2.examp() } ``` -------------------------------- ### Interactive Plotting with tkexamp Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates how to use tkexamp to create interactive plots with customizable parameters using spinboxes, sliders, comboboxes, and checkboxes. The 'wait=TRUE' option returns a list of arguments when the window is closed. ```R if(interactive()) { x <- sort( runif(25,1,10) ) y <- rnorm(25, x) # some common plotting parameters tke.test1 <- list(Parameters=list( pch=list('spinbox',init=1,from=0,to=255,width=5), cex=list('slider',init=1.5,from=0.1,to=5,resolution=0.1), type=list('combobox',init='b', values=c('p','l','b','o','c','h','s','S','n'), width=5), lwd=list('spinbox',init=1,from=0,to=5,increment=1,width=5), lty=list('spinbox',init=1,from=0,to=6,increment=1,width=5) )) tkexamp( plot(x,y), tke.test1, plotloc='top' ) # different controls for the parameters tke.test2 <- list(Parameters=list( pch=list('spinbox',init=1,values=c(0:25,32:255),width=5), cex=list('slider',init=1.5,from=0.1,to=5,resolution=0.1), type=list('radiobuttons',init='b', values=c('p','l','b','o','c','h','s','S','n'), width=5), lwd=list('spinbox',init=1,from=0,to=5,increment=1,width=5), lty=list('spinbox',init=1,from=0,to=6,increment=1,width=5), xpd=list('checkbox') )) tkexamp( plot(x,y), tke.test2, plotloc='left') tmp <- tkexamp( plot(x,y), list(tke.test2), plotloc='right', wait=TRUE ) # now recreate the plot tmp$x <- x tmp$xlab <- 'x' tmp$y <- y do.call('plot', tmp) # a non plotting example tke.test3 <- list( sens=list('slider', init=0.95, from=0.9, to=1, resolution=0.005), spec=list('slider', init=0.9, from=0.8, to=1, resolution=0.005), prev=list('slider', init=0.01, from=0.0001, to=0.1, resolution=0.0001), step=list('spinbox', init=1, from=1, to=11, width=5), n=list('numentry',init=100000, width=7) ) options(scipen=1) tkexamp( SensSpec.demo(), tke.test3 ) # now increment step and watch the console # Above example but converting it to plot tempfun <- function(sens,spec,prev,step,n) { if(missing(sens) || missing(n)) return(invisible(NULL)) tmp <- capture.output( SensSpec.demo(sens=sens,spec=spec, prev=prev, n=n, step=step) ) par(cex=2.25) plot.new() tmp2 <- strheight(tmp) text(0, 1-cumsum(tmp2*1.5), tmp, family='mono', adj=0) title('Sensitivity and Specificity Example') } tkexamp( tempfun(), tke.test3, hscale=4, vscale=2 ) # an example using trellis graphics tke.test4 <- list( alpha=list('slider', from=0,to=1,init=1, resolution=0.05), cex=list('spinbox',init=.8,from=.1,to=3,increment=.1,width=5), col=list('entry',init='#0080ff'), pch=list('spinbox',init=1, from=0,to=255, increment=1,width=5), fill=list('entry',init='transparent') ) tempfun <- function(x,y,alpha,cex,col,pch,fill) { if(missing(alpha) || missing(cex)) {return()} trellis.par.set(plot.symbol=list(alpha=alpha, cex=cex, col=col, font=1,pch=pch,fill=fill)) print(xyplot( y~x )) } require(lattice) tkexamp( tempfun(x,y), list(tke.test4), plotloc='left') # Two example using ggplot2 if( require(ggplot2) ) { ## 1 tkexamp( qplot(cty,data=mpg, geom='histogram'), list(binwidth=list('slider',from=1,to=25)), print=TRUE) ## 2 tmpfun <- function(bw=2){ print(ggplot(mpg, aes(cty)) + geom_histogram(binwidth = bw)) } tkexamp( tmpfun, list(bw=list('slider',from=1, to=5))) } } ``` -------------------------------- ### Interactive Visualization Tests Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates interactive visualization tests using `vis.test`. Requires an interactive R session. ```R if(interactive()) { x <- rexp(25, 1/3) vis.test(x, vt.qqnorm) x <- rnorm(100, 50, 3) vis.test(x, vt.normhist) } ``` -------------------------------- ### Interactive Data Visualization with TkListView Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates the use of TkListView for interactively viewing complex R data structures and model fits. Requires an interactive R session. ```R if(interactive()) { tmp <- list( a=letters, b=list(1:10, 10:1), c=list( x=rnorm(100), z=data.frame(x=rnorm(10),y=rnorm(10)))) TkListView(tmp) fit <- lm(Petal.Width ~ ., data=iris) TkListView(fit) if(require(stats4)){ # this example is copied almost verbatim from ?mle x <- 0:10 y <- c(26, 17, 13, 12, 20, 5, 9, 8, 5, 4, 8) ll <- function(ymax=15, xhalf=6) -sum(stats::dpois(y, lambda=ymax/(1+x/xhalf), log=TRUE)) (fit <- mle(ll)) TkListView(list(fit)) } } ``` -------------------------------- ### Demonstrate Maximum Likelihood Estimation Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Graphically demonstrates the concept of Maximum Likelihood Estimation (MLE) for a normal distribution. It allows interactive adjustment of mean and standard deviation parameters using Tk sliders to observe their effect on the log likelihood. ```R if(interactive()){ mle.demo() m <- runif(1, 50,100) s <- runif(1, 1, 10) x <- rnorm(15, m, s) mm <- mean(x) ss <- sqrt(var(x)) ss2 <- sqrt(var(x)*11/12) mle.demo(x) # now find the mle from the graph and compare it to mm, ss, ss2, m, and s } ``` -------------------------------- ### Demonstrate ROC curves by interactively building one Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html An interactive demonstration to understand the construction of Receiver Operator Curves (ROC). ```APIDOC ## roc.demo ### Description This demonstration allows you to interactively build a Receiver Operator Curve to better understand what goes into creating them. ### Usage ```r roc.demo(x = rnorm(25, 10, 1), y = rnorm(25, 11, 1.5)) ``` ### Arguments `x` | Data values for group 1 (controls). `y` | Data values for group 2 (cases). ### Details Density plots for the 2 groups will be created in the lower panel of the plot (colored red (group 1) and blue (group 2)) along with rug plots of the actual datapoints. There is also a green vertical line that represents a decision rule cutoff, any points higher than the cutoff are predicted to be in group 2 and points less than the cuttoff are predicted to be in group 1. The sensitivity and specificity for the current cuttoff value are printed below the plot. A Tk slider box is also created that allows you to move the cuttoff value and update the plots. As the cutoff value changes, the different combinations of sensitivity and specificity are added to the ROC curve in the top panel (the point corresponding to the current cuttoff value is highlighted in red). A line is also drawn from the point representing sensitivity and specificity both equal to 1 to the point closest to it. ### Value No meaninful value is returned, this function is run solely for the side effects. ### Author(s) Greg Snow 538280@gmail.com ### See Also `slider`, `ROC` function in package Epi, `auROC` in package limma, package ROC ### Examples ```r if(interactive()){ roc.demo() with(CO2, roc.demo(uptake[Type=='Mississippi'], uptake[Type=='Quebec'] ) ) } ``` ``` -------------------------------- ### General Data Simulation Function with Predefined Expression Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html This snippet demonstrates creating a more general simulation function using a predefined expression. It assumes specific factor level ordering ('Female', 'Male'). ```R myexpr <- quote({ n <- length(sex) h <- c(64,69) height <- h[sex] + rnorm(n,0,3) }) simheight <- simfun(eval(myexpr), drop=c('n','h')) my.df <- data.frame(sex=factor(sample(rep(c('Male','Female'),c(5,10))))) (simdat <- simheight(my.df)) ``` -------------------------------- ### Interactive 3D Map with rgl Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates creating a 3D map using the rgl package, with spheres added to the scene. Requires the spData package and interactive R session. ```R if(interactive()){ if(require("spData")) { data(world) rgl.Map(world$geom) spheres3d(0,0,0,.999, col='lightblue') } } ``` -------------------------------- ### Interactive Model Prediction GUI with TkPredict Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Launches a Tk GUI for interactively exploring model predictions by adjusting predictor values. Requires an interactive R session. ```R if(interactive()){ TkPredict(fit.lm1) TkPredict(fit.glm1) } ``` -------------------------------- ### Plot Symbols with Size and Position Arguments Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates controlling symbol size and position using `xsize`, `ysize`, and `inches` arguments. Includes reference lines for context. ```R plot( 1:10, (1:10)*100, type='n', xlab='', ylab='' ) my.symbols( 5, 500, ms.polygon, n=250, inches=1.5 ) my.symbols( 5, 500, ms.polygon, n=250, xsize=2, col='blue' ) my.symbols( 5, 500, ms.polygon, n=250, ysize=200, col='green' ) my.symbols( 5, 500, ms.polygon, n=250, xsize=2, ysize=200, col='red' ) abline( v=c(4,6), col='grey' ) abline( h=c(400, 600), col='grey' ) ``` -------------------------------- ### Simulate, Override Seed Setting Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates simulating data while overriding the default seed setting for reproducibility. It generates height data based on sex and includes random variations. ```R simheight <- simfun({ set.seed(1234) h <- c(64,69) sex <- factor(rep(c('Female','Male'),each=50)) height <- round(rnorm(100, rep(h,each=50),3),1) sex <- sex[ID] height <- height[ID] }, drop='h') (newdat <- simheight(list(ID=c(1:5,51:55)))) (newdat2<- simheight(list(ID=1:10))) ``` -------------------------------- ### Demonstrate Confidence Intervals Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Generates samples from a normal distribution and plots confidence intervals to demonstrate the concept. Supports 'z', 't', or 'both' methods for interval calculation and allows interactive adjustment of the confidence level via a Tk slider. ```R ci.examp(mean.sim = 100, sd = 10, n = 25, reps = 50, conf.level = 0.95, method = "z", lower.conf = (1 - conf.level)/2, upper.conf = 1 - (1 - conf.level)/2) ``` ```R run.ci.examp(reps = 100, seed, method="z", n=25) ``` -------------------------------- ### Demonstrate Loess Curve Internals Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Creates a scatterplot with a loess fit and interactively shows the window and case weights used for the curve at a selected x value. ```r loess.demo(x, y, span = 2/3, degree = 1, nearest = FALSE, xlim = numeric(0), ylim = numeric(0), verbose = FALSE) ``` -------------------------------- ### Create and Augment Plots with Histograms Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates creating an original plot and then adding multiple histograms to specific subplots. Requires interactive session for some parts. ```R # make an original plot plot( 11:20, sample(51:60) ) # add some histograms subplot( hist(rnorm(100)), 15, 55) subplot( hist(runif(100),main='',xlab='',ylab=''), 11, 51, hadj=0, vadj=0) subplot( hist(rexp(100, 1/3)), 20, 60, hadj=1, vadj=1, size=c(0.5,2) ) subplot( hist(rt(100,3)), c(12,16), c(57,59), pars=list(lwd=3,ask=FALSE) ) ``` -------------------------------- ### Create Dotcharts Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Generates simple dotcharts, useful as a quick visual approximation of a histogram for one or two datasets. Primarily for demonstration purposes. ```R dots( round( rnorm(50, 10,3) ) ) dots2( round( rnorm(20, 10,3) ), round(rnorm(20,12,2)) ) ``` -------------------------------- ### Create Tk Dialog Boxes for Interactive Plotting Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Creates a Tk window with a graph and controls to change plotting parameters interactively. Use this to demonstrate how parameter changes affect a plot in real-time. ```R tkexamp(FUN, param.list, vscale=1.5, hscale=1.5, wait=FALSE, plotloc='top', an.play=TRUE, print=FALSE, ...) ``` -------------------------------- ### Load Steps Data Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Loads the 'steps' dataset, which contains pedometer data collected over approximately 11 months. ```R data(steps) ``` -------------------------------- ### SensSpec.demo Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Demonstrates the calculation of Positive Predictive Value (PPV) and Negative Predictive Value (NPV) using a virtual population approach, which is more intuitive than directly applying Bayes' Rule. ```APIDOC ## SensSpec.demo(sens, spec, prev, n = 100000, step = 11) ### Description This function demonstrates how to get PPV and NPV from Sensitivity, Specificity, and Prevalence by using a virtual population rather than a direct application of Bayes Rule. This approach is more intuitive to mathphobes. ### Arguments `sens` | Sensitivity (between 0 and 1) `spec` | Specificity (between 0 and 1) `prev` | Prevalence (between 0 and 1) `n` | Size of the virtual population (large round number) `step` | which step of the process to display ### Details The common way to compute Positive Predictive Value (probability of disease given a positive test (PPV)) and Negative Predictive Value (probability of no disease given negative test (NPV)) is to use Bayes' rule with the Sensitivity, Specificity, and Prevalence. This approach can be overwhelming to non-math types, so this demonstration goes through the steps of assuming a virtual population, then filling in a 2x2 table based on the population and given values of Sensitivity, Specificity, and Prevalence. PPV and NPV are then computed from this table. This approach is more intuitive to many people. The function can be run multiple times with different values of `step` to show the steps in building the table, then rerun with different values to show how changes in the inputs affect the results. ### Value An invisible matrix with the 2x2 table ``` -------------------------------- ### Simulate Using a Fitted Model Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html This snippet shows how to use simfun with a pre-fitted linear model (lm). It predicts Fertility based on new data and adds random noise based on the model's sigma. ```R fit <- lm(Fertility ~ . , data=swiss) simfert <- simfun({ Fertility <- predict(fit, newdata=data) Fertility <- Fertility + rnorm(length(Fertility),0,summary(fit)$sigma) }, drop=c('fit'), fit=fit) tmpdat <- as.data.frame(lapply(swiss[,-1], function(x) round(runif(100, min(x), max(x))))) names(tmpdat) <- names(swiss)[-1] fertdat <- simfert(tmpdat) head(fertdat) rbind(coef(fit), coef(lm(Fertility~., data=fertdat))) ``` -------------------------------- ### Load Evap Dataset Source: https://cran.r-project.org/web/packages/TeachingDemos/refman/TeachingDemos.html Loads the 'evap' dataset, which contains daily weather variables for estimating soil evaporation. This is a standard R data loading command. ```R data(evap) ```