typestar

Factors in R

R's type for categorical data, ordered or not.

sizes <- factor(c("small", "large", "medium", "small"),
                levels = c("small", "medium", "large"),
                ordered = TRUE)

levels_of <- levels(sizes)
counts <- table(sizes)
codes <- as.integer(sizes)
is_big <- sizes > "small"

relabeled <- factor(sizes, labels = c("S", "M", "L"))
dropped <- droplevels(sizes[sizes != "medium"])

How it works

  1. levels fixes the category order explicitly.
  2. ordered = TRUE allows comparisons between levels.
  3. table counts levels; droplevels removes unused ones.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
318
Tokens
93
Three-star pace
80 tpm

At the three-star pace of 80 tokens a minute, this run takes about 70 seconds.

Type this snippet

Step 4 of 4 in Vectors & types, step 4 of 20 in Language basics.

← Previous Next →