Skip to content

Variables, types and roles

What one row stands for, what kind of thing each column records, and what job it plays. These three facts decide which methods make sense.

Introductory ~9 min7 steps

What runs in CodeSplash

You will be able to

  • Identify the unit of observation in a dataset
  • Classify a column by type, without trusting how it looks
  • Assign a role to each variable in a question

Read first

01

What one row stands for

Read

Before anything else, ask what one row is. In the penguins data one row is one bird: that is the unit of observation. A variableVariable typesWhether a column holds numbers, categories, ordered categories, yes/no values, dates or text; it decides which methods fit. is one thing recorded about each unit, such as its species or body mass.

Get the unit wrong and later analysis goes wrong too. If a table has one row per weighing, and each bird was weighed several times, the rows aren't independent birds.

Palmer penguins
02

Types decide methods

Read

Numbers don't always measure, and labels sometimes have an order.

TypeWhat it recordsExample
ContinuousA measurement on a scalebody_mass in grams
CountHow many times something happenedinfections per ward
BinaryOne of two statessupp: OJ or VC
CategoricalLabels with no orderspecies
OrdinalLabels with an orderdose_f: 0.5 < 1 < 2
DateA point in timea sign-up date
IdentifierA name for a rowa customer ID
03

Numbers or levels?

Predict

Predict first

ToothGrowth records dose as 0.5, 1 or 2 mg per day. What type is it?

ContinuousOrdinalIt depends on your question
Reveal

It depends on your question. Treated as a number, you assume growth changes along a line or curve with dose. Treated as ordered levels, each dose gets its own mean with no shape imposed. The dataset keeps both: dose and dose_f.

04

Sort these columns

Checkpoint

Check yourself

A column holds postal codes such as 10001 and 94103. What type is it?

Show the answer

Answer: b

The average postal code means nothing. Ask whether arithmetic on the values would make sense.

Check yourself

A survey item records satisfaction from 1 (very low) to 5 (very high). What type is it?

Show the answer

Answer: b

The order is real, but nothing says the step from 1 to 2 equals the step from 4 to 5. Rank-based methods respect that; averages assume it away.

Check yourself

Each row of a table is one blood-pressure reading, and patients have several readings. What is the unit of observation?

Show the answer

Answer: a

The rows are readings, nested inside patients. A method that treats every row as independent will overstate your certainty.

05

See how CodeSplash reads your columns

In the app

Open a dataset in Insights. Each column page shows the type the profiler inferred, its confidence and the evidence, and flags traps such as numbers as text.

A variable's role is the job it plays in your question: outcome, group or predictor, or a key like target, id or time. Setting roles in the data dictionary sharpens the Test Chooser's suggestions.

FrequenciesRecorded · Python and R agreeRecorded 2026-11-09 · 79 values compared
R

smoke: 4 categories; most common Never (80.1% of valid values), 1 missing.

Rows
237
Variables
3

Plots

smokeHow often does each category occur?
View data
smoke
Never
Regul
Occas
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Never
Occas
Never
Heavy
Never
Regul
Occas
Never
Never
Never
Occas
Never
Never
Never
Never
Never
Never
Regul
Never
Occas
Never
Never
Never
Never
Never
Regul
Never
Never
Never
Never
Occas

First 60 of 236 rows.

Frequencies

VariableLeveln% of rowsValid %Cumulative %95% CI low95% CI high
smokeNever18979.7%80.1%80.1%74.5%84.7%
smokeOccas198.0%8.1%88.1%5.2%12.2%
smokeRegul177.2%7.2%95.3%4.5%11.2%
smokeHeavy114.6%4.7%100.0%2.6%8.2%
smoke(missing)10.4%————
exerciseNone2410.1%10.1%10.1%6.9%14.6%
exerciseSome9841.4%41.4%51.5%35.3%47.7%
exerciseFreq11548.5%48.5%100.0%42.2%54.9%
sexFemale11849.8%50.0%50.0%43.7%56.3%
sexMale11849.8%50.0%100.0%43.7%56.3%
sex(missing)10.4%————

Valid % and intervals exclude missing values; Wilson 95% intervals.

Summary by variable

VariableLevelsValidMissingMost commonIts shareEntropy (bits)Imbalance
smoke42361Never80.1%1.0290.4856
exercise32370Freq48.5%1.3680.1371
sex22361Female50.0%10
  • Imbalance = 1 − H / log₂(k) over observed levels: 0 when levels are equally common, near 1 when one dominates.
The exact R script · R R version 4.5.1 (2025-06-13)
# Frequencies (categorical variables)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.categorical 1.0.0 · spec a79864cc287a6a99
# Dataset: s1_survey (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
variables <- c("smoke", "exercise", "sex")
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_survey.parquet", col_select = variables))
level_order <- list(
  "smoke" = c("Never", "Occas", "Regul", "Heavy"),
  "exercise" = c("None", "Some", "Freq"),
  "sex" = c("Female", "Male")
)
for (v in variables) {
  if (is.null(level_order[[v]])) level_order[[v]] <- sort(unique(as.character(df[[v]][!is.na(df[[v]])])), method = "radix")
  df[[v]] <- factor(df[[v]], levels = level_order[[v]])  # values outside the stored levels count as missing
}
conf <- 0.95
ci_method <- "wilson"  # pinned: Wilson unless chosen (Brown, Cai & DasGupta 2001)
simultaneous <- FALSE  # Goodman (1965) intervals that hold for all levels at once
ord <- "stored"
warnings <- list()

# %% Frequencies
rows <- list()
values <- list(n_rows = nrow(df))
summaries <- list()
for (v in variables) {
  x <- df[[v]]
  n_total <- length(x)
  n_missing <- sum(is.na(x))
  n_valid <- n_total - n_missing
  lv_all <- level_order[[v]]
  counts <- vapply(lv_all, function(lv) sum(x == lv, na.rm = TRUE), numeric(1))
  idx <- seq_along(counts)
  if (ord == "frequency") idx <- idx[order(-counts, idx)]
  if (simultaneous && n_valid > 0) sim <- cs_goodman_ci(counts, conf)
  cum <- 0
  for (i in idx) {
    lv <- lv_all[i]
    c <- counts[[i]]
    cum <- cum + c
    ci <- if (n_valid) cs_prop_ci(c, n_valid, conf, ci_method) else c(NaN, NaN)
    row <- list(variable = v, level = lv, n = c,
                pct = if (n_total) c / n_total else NaN,
                valid_pct = if (n_valid) c / n_valid else NaN,
                cum_pct = if (n_valid) cum / n_valid else NaN,
                ci_low = ci[1], ci_high = ci[2])
    if (simultaneous) {
      row$sim_low <- if (n_valid) sim$low[i] else NaN
      row$sim_high <- if (n_valid) sim$high[i] else NaN
    }
    rows[[length(rows) + 1]] <- row
    for (k in c("n", "pct", "valid_pct", "cum_pct", "ci_low", "ci_high", if (simultaneous) c("sim_low", "sim_high"))) {
      values[[sprintf("%s[%s|%s]", k, v, lv)]] <- row[[k]]
    }
  }
  if (n_missing) rows[[length(rows) + 1]] <- list(variable = v, level = "(missing)", n = n_missing, pct = n_missing / n_total)
  mode_i <- if (length(counts) && max(counts) > 0) which.max(counts) else NA
  ent <- cs_entropy_bits(counts)
  k_obs <- sum(counts > 0)
  summary <- list(variable = v, k = length(counts), n_valid = n_valid, n_missing = n_missing,
                  mode = if (is.na(mode_i)) "" else lv_all[mode_i],
                  mode_pct = if (is.na(mode_i) || !n_valid) NaN else counts[[mode_i]] / n_valid,
                  entropy = ent,
                  imbalance = if (k_obs > 1) 1 - ent / log2(k_obs) else NaN)
  summaries[[length(summaries) + 1]] <- summary
  for (k in c("k", "n_valid", "n_missing", "mode", "mode_pct", "entropy", "imbalance")) values[[sprintf("%s[%s]", k, v)]] <- summary[[k]]
  rare <- lv_all[counts > 0 & counts < 0.01 * n_valid]
  if (length(rare)) {
    warnings <- c(warnings, sprintf("%s: %d rare level%s (< 1%% of valid values): %s.", v, length(rare), if (length(rare) > 1) "s" else "",
                                    paste(utils::head(rare, 8), collapse = ", ")))
  }
  empty <- lv_all[counts == 0]
  if (length(empty)) warnings <- c(warnings, sprintf("%s: no observations in %s.", v, paste(utils::head(empty, 8), collapse = ", ")))
}

# %% Result
lead <- summaries[[1]]
values$lead <- lead$variable
values$n_variables <- length(variables)
pct <- sprintf("%.0f%%", conf * 100)
method_label <- c("wilson" = "Wilson", "clopper-pearson" = "Clopper–Pearson (exact)", "jeffreys" = "Jeffreys",
                  "agresti-coull" = "Agresti–Coull", "wald" = "Wald")[[ci_method]]
values$ci_method_label <- method_label
columns <- list(
  list(key = "variable", label = "Variable", type = "string"), list(key = "level", label = "Level", type = "string"),
  list(key = "n", label = "n", type = "integer"), list(key = "pct", label = "% of rows", type = "percent"),
  list(key = "valid_pct", label = "Valid %", type = "percent"), list(key = "cum_pct", label = "Cumulative %", type = "percent"),
  list(key = "ci_low", label = paste(pct, "CI low"), type = "percent"), list(key = "ci_high", label = paste(pct, "CI high"), type = "percent")
)
if (simultaneous) {
  columns <- c(columns, list(list(key = "sim_low", label = "Simultaneous low", type = "percent"), list(key = "sim_high", label = "Simultaneous high", type = "percent")))
}
v0 <- variables[1]
chart_x <- as.character(df[[v0]][!is.na(df[[v0]])])
chart_rows <- unique(round(seq(1, length(chart_x), length.out = min(length(chart_x), 5000))))
cs_publish(list(
  method = "describe.categorical",
  methodVersion = "1.0.0",
  title = "Frequencies",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = nrow(df),
  summary = sprintf("%s: %d categories; most common %s (%.1f%% of valid values), %d missing.", lead$variable, lead$k, lead$mode, 100 * lead$mode_pct, lead$n_missing),
  statistics = list(list(key = "n_rows", label = "Rows", value = nrow(df)), list(key = "variables", label = "Variables", value = length(variables))),
  tables = list(
    list(key = "frequencies", title = "Frequencies", columns = columns, rows = rows,
         note = paste0("Valid % and intervals exclude missing values; ", method_label, " ", pct, " intervals",
                       if (simultaneous) "; Goodman simultaneous intervals hold for all levels together." else ".")),
    list(key = "summary", title = "Summary by variable",
         columns = list(list(key = "variable", label = "Variable", type = "string"), list(key = "k", label = "Levels", type = "integer"),
                        list(key = "n_valid", label = "Valid", type = "integer"), list(key = "n_missing", label = "Missing", type = "integer"),
                        list(key = "mode", label = "Most common", type = "string"), list(key = "mode_pct", label = "Its share", type = "percent"),
                        list(key = "entropy", label = "Entropy (bits)", type = "number"), list(key = "imbalance", label = "Imbalance", type = "number")),
         rows = summaries)
  ),
  effectSizes = list(),
  assumptions = list(),
  warnings = warnings,
  notes = list("Imbalance = 1 − H / log₂(k) over observed levels: 0 when levels are equally common, near 1 when one dominates."),
  charts = list(cs_chart("frequencies", "bar", v0, list(x = cs_col(v0, chart_x[chart_rows], levels = level_order[[v0]])),
                         controls = list(order = if (ord == "frequency") "freq" else "alpha"))),
  values = values
))
Python

smoke: 4 categories; most common Never (80.1% of valid values), 1 missing.

Rows
237
Variables
3

To keep this page light, the plots are shown once, under the R tab.

Frequencies

VariableLeveln% of rowsValid %Cumulative %95% CI low95% CI high
smokeNever18979.7%80.1%80.1%74.5%84.7%
smokeOccas198.0%8.1%88.1%5.2%12.2%
smokeRegul177.2%7.2%95.3%4.5%11.2%
smokeHeavy114.6%4.7%100.0%2.6%8.2%
smoke(missing)10.4%————
exerciseNone2410.1%10.1%10.1%6.9%14.6%
exerciseSome9841.4%41.4%51.5%35.3%47.7%
exerciseFreq11548.5%48.5%100.0%42.2%54.9%
sexFemale11849.8%50.0%50.0%43.7%56.3%
sexMale11849.8%50.0%100.0%43.7%56.3%
sex(missing)10.4%————

Valid % and intervals exclude missing values; Wilson 95% intervals.

Summary by variable

VariableLevelsValidMissingMost commonIts shareEntropy (bits)Imbalance
smoke42361Never80.1%1.0290.4856
exercise32370Freq48.5%1.3680.1371
sex22361Female50.0%10
  • Imbalance = 1 − H / log₂(k) over observed levels: 0 when levels are equally common, near 1 when one dominates.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Frequencies (categorical variables)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method describe.categorical 1.0.0 · spec a79864cc287a6a99
# Dataset: s1_survey (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import describe as csd

# %% Data
variables = ["smoke", "exercise", "sex"]
df = pd.read_parquet("tests/parity/fixtures/s1_survey.parquet", columns=variables)
level_order = {
    "smoke": ["Never", "Occas", "Regul", "Heavy"],
    "exercise": ["None", "Some", "Freq"],
    "sex": ["Female", "Male"],
}
for v in variables:
    if not level_order[v]:  # no stored order: sorted values
        level_order[v] = sorted(str(x) for x in df[v].dropna().unique())
    df[v] = pd.Categorical(df[v], categories=level_order[v])  # values outside the stored levels count as missing
conf = 0.95
ci_method = "wilson"  # pinned: Wilson unless chosen (Brown, Cai & DasGupta 2001)
simultaneous = False  # Goodman (1965) intervals that hold for all levels at once
order = "stored"
warnings = []

# %% Frequencies
rows, values = [], {"n_rows": len(df)}
summaries = []
for v in variables:
    x = df[v]
    n_total = len(x)
    n_missing = int(x.isna().sum())
    n_valid = n_total - n_missing
    counts = np.array([int((x == lv).sum()) for lv in level_order[v]])
    idx = list(range(len(counts)))
    if order == "frequency":
        idx.sort(key=lambda i: (-counts[i], i))
    if simultaneous and n_valid > 0:
        sim_lo, sim_hi = csd.goodman_ci(counts, conf)
    cum = 0
    for i in idx:
        lv, c = level_order[v][i], int(counts[i])
        cum += c
        lo, hi = csd.prop_ci(c, n_valid, conf, ci_method) if n_valid else (float("nan"), float("nan"))
        row = {
            "variable": v, "level": lv, "n": c,
            "pct": c / n_total if n_total else float("nan"),
            "valid_pct": c / n_valid if n_valid else float("nan"),
            "cum_pct": cum / n_valid if n_valid else float("nan"),
            "ci_low": lo, "ci_high": hi,
        }
        if simultaneous:
            row["sim_low"] = float(sim_lo[i]) if n_valid else float("nan")
            row["sim_high"] = float(sim_hi[i]) if n_valid else float("nan")
        rows.append(row)
        for k in ("n", "pct", "valid_pct", "cum_pct", "ci_low", "ci_high") + (("sim_low", "sim_high") if simultaneous else ()):
            values[f"{k}[{v}|{lv}]"] = row[k]
    if n_missing:
        rows.append({"variable": v, "level": "(missing)", "n": n_missing, "pct": n_missing / n_total})
    mode_i = int(np.argmax(counts)) if counts.size and counts.max() > 0 else None
    summary = {
        "variable": v, "k": len(counts), "n_valid": n_valid, "n_missing": n_missing,
        "mode": "" if mode_i is None else level_order[v][mode_i],
        "mode_pct": float("nan") if mode_i is None or not n_valid else counts[mode_i] / n_valid,
        "entropy": csd.entropy_bits(counts),
    }
    k_obs = int((counts > 0).sum())
    summary["imbalance"] = 1 - summary["entropy"] / np.log2(k_obs) if k_obs > 1 else float("nan")
    summaries.append(summary)
    for k in ("k", "n_valid", "n_missing", "mode", "mode_pct", "entropy", "imbalance"):
        values[f"{k}[{v}]"] = summary[k]
    rare = [level_order[v][i] for i in range(len(counts)) if 0 < counts[i] < 0.01 * n_valid]
    if rare:
        warnings.append(f"{v}: {len(rare)} rare level{'s' if len(rare) > 1 else ''} (< 1% of valid values): {', '.join(rare[:8])}.")
    empty = [level_order[v][i] for i in range(len(counts)) if counts[i] == 0]
    if empty:
        warnings.append(f"{v}: no observations in {', '.join(empty[:8])}.")

# %% Result
lead = summaries[0]
values.update({"lead": lead["variable"], "n_variables": len(variables)})
pct = f"{conf:.0%}"
method_label = {"wilson": "Wilson", "clopper-pearson": "Clopper–Pearson (exact)", "jeffreys": "Jeffreys",
                "agresti-coull": "Agresti–Coull", "wald": "Wald"}[ci_method]
values["ci_method_label"] = method_label
columns = [
    {"key": "variable", "label": "Variable", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
    {"key": "n", "label": "n", "type": "integer"}, {"key": "pct", "label": "% of rows", "type": "percent"},
    {"key": "valid_pct", "label": "Valid %", "type": "percent"}, {"key": "cum_pct", "label": "Cumulative %", "type": "percent"},
    {"key": "ci_low", "label": f"{pct} CI low", "type": "percent"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "percent"},
]
if simultaneous:
    columns += [{"key": "sim_low", "label": "Simultaneous low", "type": "percent"}, {"key": "sim_high", "label": "Simultaneous high", "type": "percent"}]
v0 = variables[0]
chart_df = df[df[v0].notna()]
chart_rows = np.unique(np.round(np.linspace(0, len(chart_df) - 1, min(len(chart_df), 5000))).astype(int)) if len(chart_df) else np.array([], dtype=int)
cs.publish({
    "method": "describe.categorical",
    "methodVersion": "1.0.0",
    "title": "Frequencies",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": len(df),
    "summary": f"{lead['variable']}: {lead['k']} categories; most common {lead['mode']} ({lead['mode_pct']:.1%} of valid values), {lead['n_missing']} missing.",
    "statistics": [{"key": "n_rows", "label": "Rows", "value": len(df)}, {"key": "variables", "label": "Variables", "value": len(variables)}],
    "tables": [
        {"key": "frequencies", "title": "Frequencies", "columns": columns, "rows": rows,
         "note": f"Valid % and intervals exclude missing values; {method_label} {pct} intervals" + ("; Goodman simultaneous intervals hold for all levels together." if simultaneous else ".")},
        {"key": "summary", "title": "Summary by variable",
         "columns": [{"key": "variable", "label": "Variable", "type": "string"}, {"key": "k", "label": "Levels", "type": "integer"},
                     {"key": "n_valid", "label": "Valid", "type": "integer"}, {"key": "n_missing", "label": "Missing", "type": "integer"},
                     {"key": "mode", "label": "Most common", "type": "string"}, {"key": "mode_pct", "label": "Its share", "type": "percent"},
                     {"key": "entropy", "label": "Entropy (bits)", "type": "number"}, {"key": "imbalance", "label": "Imbalance", "type": "number"}],
         "rows": summaries},
    ],
    "effectSizes": [],
    "assumptions": [],
    "warnings": warnings,
    "notes": ["Imbalance = 1 − H / log₂(k) over observed levels: 0 when levels are equally common, near 1 when one dominates."],
    "charts": [cs.chart("frequencies", "bar", f"{v0}", {"x": cs.col(v0, chart_df[v0].astype(str).to_numpy()[chart_rows], levels=level_order[v0])},
                        controls={"order": "freq" if order == "frequency" else "alpha"})],
    "values": values,
})
06

Your own table

Reflect

Take a table you use. What does one row stand for? Which column looks numeric but isn't really? Which column would you be tempted to average when you shouldn't?

07

Recap

Recap
  • Ask what one row stands for before anything else.
  • Type depends on what a value means, not on how it looks.
  • A role is the job a variable plays in one question. The same column can change jobs between questions.

Concepts in this lesson