\[ %% % Add your macros here; they'll be included in pdf and html output. %% \newcommand{\R}{\mathbb{R}} % reals \newcommand{\E}{\mathbb{E}} % expectation \renewcommand{\P}{\mathbb{P}} % probability \DeclareMathOperator{\logit}{logit} \DeclareMathOperator{\logistic}{logistic} \DeclareMathOperator{\SE}{SE} \DeclareMathOperator{\sd}{sd} \DeclareMathOperator{\var}{var} \DeclareMathOperator{\cov}{cov} \DeclareMathOperator{\cor}{cor} \DeclareMathOperator{\Normal}{Normal} \DeclareMathOperator{\LogNormal}{logNormal} \DeclareMathOperator{\Poisson}{Poisson} \DeclareMathOperator{\Beta}{Beta} \DeclareMathOperator{\Binom}{Binomial} \DeclareMathOperator{\Gam}{Gamma} \DeclareMathOperator{\Exp}{Exponential} \DeclareMathOperator{\Cauchy}{Cauchy} \DeclareMathOperator{\Unif}{Unif} \DeclareMathOperator{\Dirichlet}{Dirichlet} \DeclareMathOperator{\Wishart}{Wishart} \DeclareMathOperator{\StudentsT}{StudentsT} \DeclareMathOperator{\Weibull}{Weibull} \newcommand{\given}{\;\vert\;} \]

R interlude: indexing

Peter Ralph

28 January 2021 – Advanced Biological Statistics

R interlude

Indexing with names is good!!

Number of ‘high’ values:

y <- rnorm(1e4)
# cutoffs:
x <- c(1, 2, 3)
sum(y > x[3])
## [1] 15

Wait, let’s make more cutoffs:

x <- c(1, 1.5, 2.5, 3)
sum(y > x[3])
## [1] 56

. . . whoops!

Wait, let’s add another level:

x <- c(low=1, "lowish"=1.5, 'highish'=2.5, high=3)
sum(y > x['high'])
## [1] 15

BUT: A warning about factors

f <- factor(c('low', 'med', 'high'))
x <- c(low=1, med=2, high=3)

What is x[f[3]]?

x[f[3]]
## low 
##   1

Defensive programming

xf <- x[f]
stopifnot(all(names(xf) == f))
## Error in templater::render_template("Week_14_Interludes.Rmd", output = "Week_14_Interludes.md", : all(names(xf) == f) is not TRUE
xf <- x[as.character(f)]
stopifnot(all(names(xf) == f))
// reveal.js plugins