Skip to content

Instantly share code, notes, and snippets.

@BroVic
Last active November 10, 2021 09:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BroVic/8cbd21aa58fa42c03308ee7a6f6fdef2 to your computer and use it in GitHub Desktop.
Save BroVic/8cbd21aa58fa42c03308ee7a6f6fdef2 to your computer and use it in GitHub Desktop.
Pre-load data for blog post
if (getRversion() < 4.1)
stop("R version 4.1 or greater is required", call. = FALSE)
dat <- mtcars
levs <-
structure(
.Data = list(c("V-shaped", "straight"), c("automatic", "manual")),
names = fcols <- c('vs', 'am')
)
for (i in fcols)
dat[[i]] <- (dat[[i]] == 0) |>
ifelse(levs[[i]][1], levs[[i]][2]) |>
as.factor()
str(dat)
(tbl.vs <- table(dat$vs))
(tbl.am <- table(dat$am))
## Naming
with(dat, table(Engine = vs, Transmission = am))
(tbl.cont <-
with(dat, table(vs, am, dnn = c("Engine", "Transmission"))))
my_useless_table_naming <- function(names) {
stopifnot(length(names) == 2)
with(dat, table(vs, am, dnn = names))
}
with(dat, table(vs, am))
with(dat, table(vs, am, deparse.level = 0))
with(dat, table(vs, am, deparse.level = 2))
table(dat$vs, dat$am, deparse.level = 2)
## Missing values
dat$vsNa <- dat$vs
is.na(dat$vsNa) <- sample(1:32, 5)
dat$vsNa
table(dat$vsNa)
table(dat$vsNa, useNA = 'ifany') ## or 'always'
with(dat, table(vsNa, am, useNA = 'ifany'))
# Multi-dimensional
dat$cyl <- as.factor(dat$cyl)
levels(dat$cyl)
with(dat, table(Cylinders = cyl, Engine = vs, Transmission = am))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment