--- title: "Describing a table and keeping its categories whole" output: rmarkdown::html_vignette vignette: > %\VignetteIndexEntry{Describing a table and keeping its categories whole} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r, include = FALSE} # the vignette runs in full in GitHub CI and for the package tarball (NOT_CRAN), # on r-universe (MY_UNIVERSE), on the package website (IN_PKGDOWN) and in an # interactive session; when CRAN re-builds it in its check, none of these is set # and only this chunk runs if (!interactive() && !any(nzchar(Sys.getenv(c("NOT_CRAN", "MY_UNIVERSE", "IN_PKGDOWN"))))) { knitr::knit_exit() } knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6.5, fig.height = 4, fig.align = "center", dpi = 72) options(width = 88) set.seed(1) library(crimlab) ``` Profiles of a data frame, frequency and correlation tables, and guards against categories that change silently. Each section is one help page: what the function is for, the example of its help page as it runs, and the plot of its result where the package draws one. `?name` gives the arguments and the value in full. # Describing a table ## Column report for a data frame `profcols()`: One row per column: type, missingness, and the summaries that suit the column's type - mean and standard deviation alongside their robust counterparts (median, MAD) for a numeric column, and the number of distinct levels plus the most common one for a categorical column. ```{r profcols} set.seed(9) df <- data.frame( # simulated columns clean = stats::rnorm(100), skewed = c(stats::rnorm(99), 500), grade = sample(c("a", "b", "c"), 100, TRUE), gappy = c(rep(NA, 10), stats::runif(90)) ) profcols(df) # The mean and the median agree on `clean` and disagree sharply on # `skewed`, which is the outlier announcing itself. p <- profcols(df) p[p$column %in% c("clean", "skewed"), c("column", "mean", "median")] # The histogram column shows shape no summary number carries. p[, c("column", "hist")] # Zeros, negatives and infinities are counted separately, because # each breaks a different downstream computation (a log, a square # root, an average). p[, c("column", "nzero", "nneg", "ninf")] # deciles instead of quartiles names(profcols(df, qnts = c(0.1, 0.9))) # a table with no columns has nothing to profile try(profcols(df[, 0])) ``` ## Inline histogram for a numeric vector `inlhist()`: Draws a one-line sketch of a column's distribution, as block characters (or ASCII where the console cannot render them). The point is density of information: a mean and a standard deviation cannot tell you a column is bimodal, skewed or has a gap, and this can, in the width of a table cell. `profcols` shows one for every numeric column. ```{r inlhist} set.seed(1) # A symmetric distribution peaks in the middle (simulated values). inlhist(stats::rnorm(1000)) # A skewed one leans left. inlhist(stats::rexp(1000)) # Bimodality is visible here and in no single summary number. inlhist(c(stats::rnorm(500, -3), stats::rnorm(500, 3))) # A constant column has no spread to show. inlhist(rep(5, 10)) # more bins for more detail inlhist(stats::rexp(1000), bins = 30) # text is not a distribution try(inlhist(c("a", "b"))) ``` ## Frequency table for one column `freqtbl()`: Counts how often each value of a column occurs, with percentages of all rows and of the non-missing rows, and missing values counted as their own row. It is the first look at a categorical variable (a charge type, a region, a response category). ```{r freqtbl} df <- data.frame(grade = c("a", "b", "b", "c", NA, "b")) freqtbl(df, "grade") # The two percentage columns differ exactly by the missingness. freqtbl(df, "grade")[, c("pct", "pctvalid")] # A vector works directly. freqtbl(c(1, 1, 2, 3, 3, 3)) # Sorted value order rather than frequency order. freqtbl(c("c", "a", "b", "a"), sort = FALSE) # Long tails are folded so the percentages still total 100. set.seed(1) ft <- freqtbl(sample(letters, 500, TRUE), maxlvl = 5) ft sum(ft$pct) # a data frame needs a column name try(freqtbl(df)) ``` ## Full pairwise correlation table `cortbl()`: Computes the correlation of every pair of numeric columns and returns it in long form - one row per pair, which is easier to sort, filter and join than a matrix - with the number of complete pairs each figure rests on. ```{r cortbl} set.seed(1) df <- data.frame(a = stats::rnorm(100), b = stats::rnorm(100)) df$c <- df$a + stats::rnorm(100, sd = 0.2) # simulated cortbl(df) # Pearson instead of Spearman cortbl(df, mthd = "pearson") # nprs shows how much data each figure rests on. gappy <- df gappy$a[1:80] <- NA cortbl(gappy) # A pair with too little overlap is NA, not a number from nothing. thin <- df thin$a[1:99] <- NA cortbl(thin)$correlation # one numeric column cannot be correlated try(cortbl(data.frame(a = 1:5, b = letters[1:5]))) ``` ## Strongest pairwise correlations in a data frame `topcors()`: Ranks the numeric column pairs by the strength of their association and returns the strongest, so a wide table's structure can be read without squinting at a correlation matrix. Use it on a new data set to find near-duplicate columns, derived columns and the relationships worth a closer look. ```{r topcors} set.seed(1) n <- 200 df <- data.frame( a = stats::rnorm(n), b = stats::rnorm(n), grade = sample(letters[1:3], n, TRUE) ) df$c <- df$a * 2 + stats::rnorm(n, sd = 0.1) # strongly related to a df$d <- exp(df$a) # monotone but curved topcors(df) # The curved pair is ranked correctly by Spearman and understated by # Pearson, which is why Spearman is the default. tc <- topcors(df, mthd = "spearman") tc[tc$x == "a" & tc$y == "d", "correlation"] tp <- topcors(df, mthd = "pearson") tp[tp$x == "a" & tp$y == "d", "correlation"] # Filter to the pairs worth looking at, and keep the top two. topcors(df, n = 2, minabs = 0.5) # a threshold above 1 is an error try(topcors(df, minabs = 2)) ``` ## Drop empty or constant columns and rows `drpempty()`, `drpconst()`: `drpempty()` removes rows or columns that are entirely missing. `drpconst()` removes columns that hold a single distinct value. Use them after reading a spreadsheet export, which often carries blank padding rows, empty columns and columns that repeat one value (a year, a jurisdiction) on every row. ```{r drp} df <- data.frame( keep = c(1, 2, NA), allna = c(NA, NA, NA), constant = c(7, 7, 7) ) drpempty(df) attr(drpempty(df), "dropped") drpconst(df) attr(drpconst(df), "dropped") # Rows only. drpempty(data.frame(a = c(1, NA), b = c(2, NA)), which = "rows") # A column of NAs plus one value is constant by default, and not when # NA is treated as a value of its own. x <- data.frame(v = c(NA, NA, 5)) ncol(drpconst(x)) ncol(drpconst(x, naasval = TRUE)) # only data frames try(drpempty(c(1, NA))) ``` ## Tidy the column names of an ingested table `clncolnms()`: Converts column names to a consistent, syntactically valid form: transliterated to ASCII, non-alphanumerics collapsed to a single separator, and duplicates disambiguated with a numeric suffix. Use it right after reading an open-data file, so the rest of the script can refer to columns without backticks. ```{r clncolnms} clncolnms(c("Total Population (2021)", "% change", "Ville / City", "dup", "dup")) # Applied to a data frame, with the original names retained. df <- data.frame(`Total Pop` = 1:2, `% change` = 3:4, check.names = FALSE) cleaned <- clncolnms(df) names(cleaned) attr(cleaned, "orignms") # Other cases. clncolnms("Total Pop", case = "lower_camel") clncolnms("Total Pop", case = "upper_camel") clncolnms("Total Pop", case = "screaming_snake") # a different separator, and a name that starts with a digit clncolnms(c("2021 count", "Rate per 1000"), sep = ".") # an unknown case is an error try(clncolnms("a b", case = "kebab")) ``` ## Multivariate outliers by Mahalanobis distance `mahaoutl()`: Finds the rows of a numeric table that are unusual as a combination of values, not just on one variable at a time, and gives each row a distance, a p-value and an outlier flag. Use it before modelling to find records that are probably data-entry or linkage errors. ```{r mahaoutl} set.seed(1) n <- 200 df <- data.frame(height = stats::rnorm(n, 170, 10)) # simulated df$weight <- df$height * 0.5 + stats::rnorm(n, 0, 5) # A row that is ordinary on each variable but unlikely jointly: # short and heavy. df[1, ] <- list(height = 155, weight = 100) out <- mahaoutl(df) head(out, 3) # It is flagged, although both values lie inside the other rows' ranges. out$row[1] == 1 range(df$height[-1]) range(df$weight[-1]) # A cluster of bad rows drags the mean toward itself; the median and # MAD move less, so the robust distance of such a row is the larger. bad <- df bad[2:21, ] <- list(height = 150, weight = 110) dclassical <- mahaoutl(bad, robust = FALSE) drobust <- mahaoutl(bad, robust = TRUE) dclassical$distance[dclassical$row == 2] < drobust$distance[drobust$row == 2] # A duplicated column has no distance defined, and is refused. dup <- df dup$height2 <- dup$height try(mahaoutl(dup)) ``` ## Runs of consecutive missing values `missruns()`: Finds the maximal stretches of consecutive `NA` in each column, with where each begins and how long it is. ```{r missruns} # One long outage and two isolated gaps, with the same total count. df <- data.frame( outage = c(1, 2, NA, NA, NA, NA, 7, 8), scattered = c(1, NA, 3, 4, NA, 6, NA, NA) ) sum(is.na(df$outage)) == sum(is.na(df$scattered)) missruns(df) # Isolated gaps too, by lowering the threshold. missruns(df, minrun = 1) # A complete column has no runs. missruns(data.frame(x = 1:5)) try(missruns(df, minrun = 0)) ``` ## Text map of where the missing values are `missgrid()`: Draws the missingness of a whole table as a grid, one character per cell block, a console map that needs no graphics device, so it works over a terminal connection, in a log, and in a plain-text summary. ```{r missgrid} set.seed(1) df <- data.frame( complete = 1:100, block = c(rep(NA, 30), 31:100), scattered = ifelse(stats::runif(100) < 0.3, NA, 1), # simulated gaps mostlygone = c(1:10, rep(NA, 90)) ) missgrid(df) # a coarser map with short labels missgrid(df, height = 5, width = 4) try(missgrid(df, height = 0)) ``` ## Which columns are missing together `misspat()`: Counts the distinct PATTERNS of missingness across rows - which combination of columns is missing in each row - rather than the per-column rates `profcols` reports. Use it before deciding how to handle gaps (drop rows, impute, model separately), because the right choice depends on whether columns are missing together. ```{r misspat} # Two columns missing in the SAME rows: one structural gap. structural <- data.frame( id = 1:10, a = c(rep(NA, 3), 4:10), b = c(rep(NA, 3), 4:10) ) misspat(structural) # The same per-column rates, but missing independently. scattered <- data.frame( id = 1:10, a = c(rep(NA, 3), 4:10), b = c(1:7, rep(NA, 3)) ) misspat(scattered) # A complete frame has exactly one pattern. misspat(data.frame(x = 1:3, y = 4:6)) # keep only the most common pattern misspat(scattered, maxpat = 1) # a frame without columns has no patterns try(misspat(data.frame())) ``` ## Missingness in one line per question `misssmry()`: The scalar summaries of missingness: how much of the table is missing, how many rows are complete, and how many columns have any or only missing values. Use it as a first look at a new extract, or to report data completeness in a methods section; `misspat` then shows which columns are missing together. ```{r misssmry} df <- data.frame(a = c(1, NA, 3), b = c(NA, NA, 3), c = 1:3) misssmry(df) # A complete table is all zeros but for its dimensions. misssmry(data.frame(x = 1:3, y = 4:6)) # a wholly empty column ms <- misssmry(data.frame(x = 1:4, note = NA)) ms[c("pct_missing", "n_cols_all_missing")] # a vector is not a table try(misssmry(c(1, NA, 3))) ``` ## Little's test for data missing completely at random `mcartst()`: Tests the MCAR assumption: that whether a value is missing is unrelated to any value in the data, observed or not. ```{r mcartst} set.seed(1) n <- 300 x <- stats::rnorm(n) # simulated y <- x + stats::rnorm(n) # Missing completely at random: a coin flip decides, so the test # should not reject. mcar <- data.frame(x = x, y = y) mcar$y[sample(n, 90)] <- NA mcartst(mcar) # Missing depending on the OTHER, observed variable: not MCAR, and # detectable, because the pattern's mean of x is shifted. mar <- data.frame(x = x, y = y) mar$y[x > 0.4] <- NA mcartst(mar) # Complete data has one pattern and nothing to test. mcartst(data.frame(a = x, b = y))$df # A duplicated column makes the likelihood degenerate, and is refused. dup <- mcar dup$x2 <- dup$x try(mcartst(dup)) ``` ## Multiple imputation by predictive mean matching `mipmm()`: Fills the missing values of numeric columns `m` times by predictive mean matching, each completed data set from its own chain of chained equations, and pools an analysis of the completed data sets by Rubin's rules: the step after `mcartst()` has said how the values are missing. Predictive mean matching imputes only values that were observed, so an imputed count stays a whole number and an imputed age stays in its range (van Buuren 2018, sec. 3.4). ```{r mipmm} set.seed(11) n <- 200 d <- data.frame(age = round(runif(n, 18, 60)), male = rbinom(n, 1, 0.5)) d$priors <- rpois(n, exp(-1 + 0.04 * d$age)) d$days <- round(20 + 3 * d$priors + 5 * d$male + rnorm(n, sd = 5)) d$priors[sample(n, 40)] <- NA d$days[sample(n, 30)] <- NA r <- mipmm(d, c("priors", "days"), c("age", "male"), fy = "days", fx = c("priors", "male"), seed = 1) r head(r$imp$priors) ``` ## Duplicated rows, with their groups `duprows()`: Returns the rows that share a combination of `cols` with at least one other row, grouped so the duplicates sit together. A duplicate is usually a join that fanned out or a re-release appended rather than replaced, both of which are visible only once the offending rows are in front of you. ```{r duprows} df <- data.frame( id = c(1, 2, 2, 3, 3, 3), value = c("a", "b", "b", "c", "d", "c") ) # Duplicated on every column. duprows(df) # Duplicated on the identifier alone, which catches more. duprows(df, "id") # No duplicates gives zero rows, not an error. duprows(data.frame(x = 1:3)) # a column that does not exist is an error try(duprows(df, "code")) ``` ## Fit and rank candidate distributions `dstfit()`: Fits candidate distributions to one numeric variable by maximum likelihood, ranks them by AIC, and reports for each the BIC, a Kolmogorov-Smirnov distance, an Anderson-Darling statistic and percentile bootstrap intervals for its parameters. A Hill estimate of the tail index is added for positive data. Use it to choose the model of a count of offences, a sentence length or a time to reoffending before modelling it. ```{r dstfit} set.seed(1) x <- stats::rgamma(300, shape = 2, rate = 0.5) # simulated f <- dstfit(x, nboot = 20) f f$fits$gamma # simulated counts with extra zeros n <- ifelse(stats::runif(300) < 0.3, 0, stats::rpois(300, 4)) dstfit(n, nboot = 0)$table[, c("family", "aic")] # a family the data do not allow try(dstfit(c(-1, 2, 3, 4, 5), fams = "gamma")) ``` ## Do distinct groups differ? A heterogeneity test before pooling `dstntst()`: Tests whether the estimates of one indicator for distinct groups (First Nations, Metis and Inuit; Aboriginal and Torres Strait Islander people; any groups with published intervals) differ more than their intervals allow, and says how much of their spread is real: the evidence for reporting each group distinctly rather than as one pooled figure. ```{r dstntst} # your own table: made-up numbers, with the pooled row named own <- data.frame( group = c("Aboriginal", "Torres Strait Islander", "Both"), est = c(24.0, 31.0, 24.6), lo = c(22.1, 26.2, 22.8), hi = c(25.9, 35.8, 26.4) ) dstntst(own, "group", "est", "lo", "hi", pooled = "Both") # simulated victimisation rates of three police divisions div <- data.frame( division = c("North", "Central", "South"), rate = c(4.1, 5.3, 4.4), lo = c(3.6, 4.7, 3.9), hi = c(4.6, 5.9, 4.9) ) dstntst(div, "division", "rate", "lo", "hi") ``` # Categorical integrity ## Recode categories by name `grdrcd()`, `deccodes()`, `relbl()`: `grdrcd()` recodes a categorical column by an explicit mapping from old to new labels and refuses any observed value the mapping does not name: silent pass-through is how group labels get corrupted. `deccodes()` decodes numeric category codes with a code-to-label dictionary (codes as names), the step that turns the codes of an imported file into its categories. `relbl()` relabels a variable by name, never by position, and returns a factor whose levels follow the mapping. ```{r grdrcd} # simulated race codes of an imported file codes <- c(1, 2, 2, 3, 1, NA) deccodes(codes, c("1" = "White", "2" = "Black", "3" = "Indigenous")) grdrcd(c("M", "F", "F", "X"), c(M = "Male", F = "Female"), keep = "X") relbl(factor(c("a", "b", "a")), c(a = "Adult", b = "Youth")) try(grdrcd(c("M", "F", "U"), c(M = "Male", F = "Female"))) ``` ## A factor with declared, verified levels `grdlvls()`: Builds a factor whose levels are exactly the ones declared, in the declared order, and refuses any value outside them. A declared reference must be the first level, so the group every model contrast is measured against is stated rather than left to alphabetical order. ```{r grdlvls} grdlvls(c("Male", "Female", "Male"), c("Male", "Female"), ref = "Male") try(grdlvls(c("Male", "Female", "X"), c("Male", "Female"))) try(grdlvls("Male", c("Male", "Female"), ref = "Female")) ``` ## Decode a labelled import by its value labels `declbld()`: Decodes a column of codes by the value labels it carries (the `labels` attribute that readers of SPSS, Stata and SAS files attach, a named vector label = code), or by `vlabs` (code = label) when it carries none. The codes alone are not the categories: decoding by code keeps every observation with its own label whatever order the labels are listed in. ```{r declbld} x <- structure(c(2, 1, 3, 2), labels = c(Female = 1, Male = 2, Other = 3)) declbld(x) declbld(c(10, 20, 10), c("20" = "Remand", "10" = "Sentenced")) try(declbld(c(1, 2))) ``` ## Refuse a categorical column where a 0/1 indicator is required `grdbin()`: Checks that a column meant as a numeric 0/1 indicator (a treatment, an outcome) is one. A factor or text column is refused rather than converted: `as.numeric()` on a factor returns the level indices (1, 2, ...), not the data, and a mis-ordered level relabels every observation. Encode it explicitly first, for example `as.integer(x == "treated")`. ```{r grdbin} grdbin(c(0, 1, 1, NA), "custody") try(grdbin(factor(c("no", "yes")), "custody")) try(grdbin(c(0, 1, 2), "custody")) ``` ## Prove a recode with a before/after cross-tabulation `vrfrcd()`: Cross-tabulates the original and the recoded column and checks that the recode is a function of the original label (no category was split between two new ones), that it follows the declared mapping (a value the mapping does not name must be unchanged), that no row was lost or added and that missingness did not change. This is how swapped groups are caught before any model runs. ```{r vrfrcd} o <- c("M", "F", "F", NA) m <- c(M = "Male", F = "Female") vrfrcd(o, grdrcd(o, m), m) try(vrfrcd(o, c("Female", "Male", "Male", NA), m)) ``` ## Verify recoded counts against the counts a release published `vrfmrg()`: Counts each label of `x` and compares the counts with those the source published (a table's margins, an annual report). When they differ and some permutation of the labels would make them agree (up to seven labels are searched), the labels are attached to the wrong groups, and the message says which. ```{r vrfmrg} x <- rep(c("White", "Black", "Indigenous"), c(50, 30, 20)) vrfmrg(x, c(White = 50, Black = 30, Indigenous = 20)) vrfmrg(x, c(White = 30, Black = 50, Indigenous = 20), strict = FALSE) ``` ## Verify a categorical variable that crossed from one program to another `xfrvrf()`: Checks a categorical column after it was exported by one program and imported by another: the value labels that arrived must agree with the source's code book, and the decoded values must reproduce the counts the source reported. When the column carries a `labels` attribute it is decoded by it (`declbld()`); otherwise by `codebook`; otherwise the values are taken as labels. ```{r xfrvrf} imp <- structure(c(1, 2, 2, 1, 1), labels = c(No = 1, Yes = 2)) xfrvrf(imp, c(No = 3, Yes = 2), codebook = c("1" = "No", "2" = "Yes")) xfrvrf(c("No", "Yes", "Yes"), c(No = 1, Yes = 2)) ``` # Text ## Transliterate text to plain ASCII `toascii()`: Converts text to plain 7-bit ASCII: the common Latin accents and ligatures are folded to their nearest ASCII letters (an accented capital A becomes `"A"`, sharp s `"ss"`, the ae ligature `"ae"`, thorn `"th"`), and every character with no folding is dropped. Use it for destinations that accept only ASCII (a file name, a fixed-width export, a legacy system), so that a name written with an accented letter arrives with the plain letter rather than as an encoding error or a question mark. ```{r toascii} toascii("Prof. \u00c1ngela Zorro Medina") toascii(c("Se\u00e1n", "Zo\u00eb", "na\u00efve", "\u0141\u00f3d\u017a")) all(charToRaw(toascii("caf\u00e9")) < 128) toascii(c(NA, "two\nlines")) ``` ## Use text as it is, falling back to ASCII when it is not valid UTF-8 `asciifb()`: Returns `x` unchanged when it is valid UTF-8 (so an accented name is kept), and transliterates to plain ASCII with `toascii()` only the elements that are not valid UTF-8 (an encoding error), or every element when `force = TRUE` (for an ASCII-only destination). Names keep their accents wherever UTF-8 is supported and degrade gracefully where it is not. ```{r asciifb} asciifb("\u00c1ngela") asciifb("\u00c1ngela", force = TRUE) bad <- rawToChar(as.raw(c(0x63, 0x61, 0x66, 0xe9))) validUTF8(bad) asciifb(bad) ``` ## Write text as UTF-8, falling back to ASCII where it is not UTF-8 `wrtxtfb()`: Writes `text` to `path` as UTF-8, one element per line, for generated text files (a README, a citation, a script) whose content may hold names with accents. An element that is not valid UTF-8 is written as its ASCII transliteration (`asciifb()`), so the file is always valid UTF-8. ```{r wrtxtfb} p <- wrtxtfb(c("line one", "line two"), tempfile(fileext = ".txt")) readLines(p) q <- wrtxtfb("Author: \u00c1ngela Zorro Medina", tempfile()) readBin(q, "raw", 20) try(wrtxtfb("x", c("a.txt", "b.txt"))) ```