Strings and Factors in R

Strings, Factors, Dates and Missing Values in R

Real data rarely arrives clean. Learn to work with the column types that cause most cleaning work in R: build conditions with logical vectors, transform and summarize numbers, clean and split text with stringr and regular expressions, recode categories with factors and forcats, and parse and calculate with dates and times in lubridate. Throughout, you decide deliberately what each missing value means, and how to count, fill, keep or drop it.

IntermediateLesson 5 of 7 in Data Analysis with R Course

What you will learn

  1. Build and combine conditions, use logical vectors to count and recode values, and transform, rank and summarize numeric columns.
    • Compare values and combine conditions
      Write comparisons that return logical vectors, combine them with Boolean operators and %in%, and predict how missing values and decimal rounding affect the result.
    • Count, test and recode with logical vectors
      Summarize conditions with sum(), mean(), any() and all(), subset with logical vectors, and create new values with if_else() and case_when().
    • Parse and transform numbers
      Turn text into numbers, use vectorized arithmetic and recycling safely, and round, bin and accumulate numeric columns.
    • Rank, shift and summarize numbers
      Rank values, compare each value with the one before it, and choose summaries of center, spread and position that suit the data.
  2. Create and combine strings, tidy and split messy text columns, and use regular expressions to detect, count, replace and extract patterns.
    • Create and combine strings
      Write strings with quotes, escapes and raw strings, see their real contents, and combine them with str_c(), str_glue() and str_flatten().
    • Inspect, tidy and split strings
      Measure and cut strings, fix case and whitespace, sort text with language rules, and split one text column into several columns or rows.
    • Write regular expression patterns
      Build patterns from literal characters, metacharacters, quantifiers, character classes, anchors and groups, and write them correctly as R strings.
    • Detect, count, replace and extract patterns
      Use regular expressions with stringr and tidyr to filter rows, count matches, clean values, pull out parts of strings and split columns.
  3. Store categorical variables as factors with deliberate levels, reorder levels for clear tables and plots, and rename, combine and lump levels with forcats.
    • Create factors with the right levels
      Explain what a factor is, create one with explicit levels, catch values that do not fit, and use ordered factors and conversions safely.
    • Reorder factor levels for tables and plots
      Order levels by a summary, by frequency or by hand, so that tables, bar charts and legends read clearly.
    • Rename, combine and lump factor levels
      Change level labels with fct_recode(), merge levels with fct_collapse(), group rare levels into an "Other" level, and handle missing and unused levels.
  4. Create dates and date-times from text and columns, extract and round their components, and calculate with time spans and time zones correctly.
    • Create dates and date-times from data
      Choose between dates, times and date-times, and create them from text, numbers or separate columns, resolving ambiguous formats.
    • Extract, round and update date components
      Pull out years, months, weekdays and hours, round date-times to a unit for grouping, and change individual components.
    • Calculate with time spans and time zones
      Measure time with durations, periods and intervals, add days and months correctly, and convert between time zones.
  5. Find, count and handle explicit missing values, reveal values that are missing without a trace, and decide in each case what a missing value means.
    • Find and handle explicit missing values
      Count missing values, tell NA from NaN, turn placeholder codes into NA, fill or replace values with care, and decide when to drop rows.
    • Reveal implicit missing values and empty groups
      Recognize rows that are absent from the data, make them visible with pivot_wider() and complete(), and report empty factor groups correctly.

Strings and Factors in R study guide

5 chapters

1

Work with logical and numeric vectors

A condition such as "above 24 °C" becomes a vector of true, false, and unknown answers in R. You can combine those answers, count them, and use them to create labels. Numeric work then adds another choice: whether a calculation should return one value per row or a summary for a whole group. Reading the output size, row order, and missing values helps you catch errors that can otherwise produce plausible results.

1.1 Compare values and combine conditions

Logical vectors let you ask the same question of every value in a column. Each answer is TRUE, FALSE, or NA, meaning unknown.

Compare one element at a time

The operators <, <=, >, >=, ==, and != compare corresponding values. Load dplyr for the examples that use its helpers.

library(dplyr)
temps <- c(18.5, 22.1, NA, 30.4, 25.0)
temps > 24
# FALSE FALSE NA TRUE TRUE

The third answer stays unknown because the third temperature is missing. Use two equals signs to test equality: x == 5. Inside filter(), x = 5 names an input instead of comparing values, and dplyr reports an error.

Calculated decimals need special care. Binary storage introduces tiny rounding errors: 0.1 + 0.2 == 0.3 is FALSE. Use near(0.1 + 0.2, 0.3), which returns TRUE using a small tolerance. This also matters for calculations such as sqrt(2)^2.

Combine complete conditions
OperatorMeaningExample
&Both conditions holdtemps > 20 & temps < 30
|At least one holdstemps < 20 | temps > 30
!Reverse a logical answer!(temps > 24)
xor()Exactly one holdsxor(temps < 20, temps > 30)

Parentheses make grouped conditions easier to read. Conditions separated by commas inside filter() are joined with &: all must hold for a row to remain. Use & and | for columns. The scalar forms && and || expect single logical values; in R 4.3 and later, longer vectors cause an error.

Missingness follows the question's logic. TRUE | NA is TRUE: the known true side already settles an "or" question. FALSE & NA is FALSE: both sides cannot be true. By contrast, TRUE & NA and FALSE | NA remain NA, because the unknown side could change the answer.

Test missingness and membership

Do not compare a value with NA using ==. Even NA == NA is NA. Use is.na() to get a definite logical answer for each position:

is.na(c(1, NA, 3))
# FALSE TRUE FALSE

For membership in a list, use %in%:

month <- c(1, 6, 11, 12)
month %in% c(11, 12)
# FALSE FALSE TRUE TRUE

The expression month == 11 | 12 does not ask whether the month is 11 or 12. R evaluates the comparison and then combines it with the bare number 12, which counts as TRUE; every position becomes true. Both sides of | need complete conditions, such as month == 11 | month == 12.

%in% can also match a missing value: NA %in% NA is TRUE. For a column containing 3, 5, and NA, x %in% c(3, NA) selects 3 and the missing value. The expression x == 3 | x == NA selects only 3 in filter(), because filter() keeps only definite TRUE results.

Key Takeaways

  • Use == for equality and near() for calculated decimal equality.
  • Combine column conditions with &, |, !, and xor().
  • Use is.na() to test missingness; comparisons with NA stay unknown.
  • Use %in% to test membership in a set, including NA when it is listed.

1.2 Count, test and recode with logical vectors

A logical vector can do more than filter rows. It can count events, test a whole group, or choose a label for each observation.

Count true answers and keep the denominator clear

R treats TRUE as 1 and FALSE as 0 in arithmetic. For c(TRUE, FALSE, TRUE, TRUE), sum() gives 3 and mean() gives 0.75. In a table of delays, summarize(n_late = sum(delay > 15)) counts late rows, while mean(delay > 15) gives their share.

library(dplyr)
temps <- c(18.5, 22.1, NA, 30.4, 25.0)
sum(temps > 24, na.rm = TRUE)
# 2
mean(temps > 24, na.rm = TRUE)
# 0.5

Without na.rm = TRUE, both summaries are NA. Removing the unknown comparison leaves four known readings. The result means two of four known temperatures were above 24 °C; it does not mean half of all five readings were warm.

any() asks whether at least one answer is true. any(temps > 30) is TRUE, settled by 30.4. all() asks whether every answer is true. all(temps > 15) is NA: the missing reading could violate the condition. With na.rm = TRUE, all() tests only the known readings.

Subset a vector or filter a table

Base subsetting retains unknown positions. temps[temps > 24] returns NA 30.4 25.0. In a data frame, filter(df, t > 24) keeps only the two known warm rows. To retain missing readings too, write filter(df, t > 24 | is.na(t)).

Choose between two outcomes

if_else() returns one result for each logical answer. Its true and false branches need compatible types.

if_else(temps > 24, "warm", "mild", missing = "unknown")
# "mild" "mild" "unknown" "warm" "warm"

The missing argument names the outcome for an unknown condition. Without it, the third result is NA. A branch containing "warm" and another containing numeric 0 cause a type error; use two text labels or two compatible numeric values. A plain NA can adapt to the other branch's type.

Put specific rules first

case_when() handles several outcomes with condition ~ value pairs. The first true condition wins for each position.

case_when(
  is.na(temps) ~ "missing",
  temps >= 25 ~ "hot",
  temps >= 20 ~ "warm",
  .default = "cool"
)
# "cool" "warm" "missing" "hot" "hot"

The 30.4 reading meets both temperature conditions but receives "hot" because that rule comes first. If temps >= 20 came first, it would catch the hot readings as well. Check an exact boundary, a value between boundaries, and a missing value when testing such code.

An unknown condition is not a match. Without the first missingness rule, the missing reading would reach .default and be mislabeled "cool". Without .default, unmatched values become NA. Choose if_else() for one yes/no split and case_when() for several rules; use cut() when the categories are ranges of one numeric column.

Key Takeaways

  • sum(condition) counts true values; mean(condition) gives their proportion.
  • na.rm = TRUE changes the set of observations a summary describes.
  • any() needs one true value; all() needs every value to be true.
  • if_else() chooses between compatible values and can label missing conditions.
  • case_when() uses the first true rule; handle missing values before a catch-all default.

1.3 Parse and transform numbers

Numeric cleaning starts with how values are read, then moves to what each calculation returns. A column of text containing numbers is still text until it is parsed.

Read the number that the text represents

R distinguishes integers, such as 1L or 1:3, from doubles, such as 1 or 2.5. Both support ordinary arithmetic; dividing integers produces a double. Use typeof() when the storage type matters.

readr's parse_number() finds the first number in each string and ignores surrounding text:

library(readr)
parse_number(c("1,250.75", "45%", "Price: 30 kg"))
# 1250.75 45 30
parse_number("1.234,5",
  locale = locale(decimal_mark = ",", grouping_mark = "."))
# 1234.5

A percent sign is removed, so "45%" becomes 45, not 0.45. Divide by 100 when you need a proportion. Text such as "n/a" becomes NA with a parsing problem. The locale describes the input file's marks; R code itself always uses a decimal point.

Read arithmetic element by element

Base arithmetic recycles a shorter vector. c(1, 2, 3, 4) + c(10, 20) gives 11 22 13 24. Recycling one constant, as in price * 1.2, is useful. Recycling a longer pattern can silently attach the wrong value to a row. If lengths do not divide evenly, R warns but still computes.

This is why month == c(1, 2) is not a membership test. It compares alternating rows with 1 and 2. For month <- c(1, 1, 2, 2, 3), it finds only two matches; month %in% c(1, 2) finds four.

NeedFunctionExample result
One minimum overallmin(c(3, 8, 5), 6)3
A cap for every elementpmin(c(3, 8, 5), 6)3 6 5
A lower limit of zeropmax(c(-2, 4), 0)0 4
Split, round, and bin values

Integer division %/% counts whole units; %% gives the remainder. For 135 minutes, 135 %/% 60 is 2 and 135 %% 60 is 15. For the clock code 1430, dividing by 100 gives hour 14 and remainder 30.

round(1234.567, 2) gives 1234.57; round(1234.567, -2) gives 1200. Exact halfway values go to the even digit: 2.5 rounds to 2 and 3.5 to 4. floor(-2.7) is -3 because "down" means toward smaller numbers; ceiling(-2.7) is -2. To round 2.13 to the nearest 0.25, use round(2.13 / 0.25) * 0.25, giving 2.25.

cut() returns a factor of ranges. With breaks c(0, 18, 65, Inf), the default intervals include their upper endpoint, so 18 belongs to (0,18]. Set right = FALSE for lower-inclusive intervals such as [18,65). Values outside the breaks become NA; check the smallest boundary as well as the internal ones.

Accumulate in a meaningful order

cumsum(c(5, 3, 8, 2)) gives 5 8 16 18. Running minima, maxima, products, and means use cummin(), cummax(), cumprod(), and cummean(). Arrange rows by the sequence you mean before calculating a running result.

Key Takeaways

  • parse_number() extracts numeric text; locale settings describe its decimal and grouping marks.
  • Recycling one constant is useful; recycling a pattern can misalign rows.
  • pmin() and pmax() return elementwise limits, while min() and max() summarize.
  • Check rounding rules and which endpoints cut() includes.
  • Arrange rows before running totals or other cumulative calculations.
  • %/% gives whole units and %% gives the remainder.

1.4 Rank, shift and summarize numbers

A numeric column can describe position, change, or a whole distribution. Choose a function by the question, then check whether row order, ties, or extreme values affect its answer.

Decide what ties should mean
library(dplyr)
s <- c(5, 8, 8, 12)
min_rank(s)    # 1 2 2 4
dense_rank(s)  # 1 2 2 3
row_number(s) # 1 2 3 4

min_rank() gives tied values the lowest shared rank, leaving a gap afterward. dense_rank() leaves no gap. row_number() gives distinct positions and breaks ties by their order. Add desc() to rank largest first: min_rank(desc(s)) gives 4 2 2 1. Missing values receive missing ranks.

A rank cutoff can retain more rows than its number suggests. For scores 90, 85, 85, 70, and 95, the descending ranks are 2, 3, 3, 5, and 1. Filtering ranks at most 3 keeps four rows. slice_max(df, score, n = 3) also keeps boundary ties by default.

For proportional position, cume_dist(s) gives 0.25 0.75 0.75 1: the fraction less than or equal to each value. percent_rank() expresses the lowest shared rank relative to the available rank range; for this vector it gives 0, one third, one third, and 1. They answer different questions when values tie.

Compare neighboring observations

lag() shifts values one position later; lead() shifts them one position earlier. Each fills the exposed position with NA.

steps <- c(7200, 8100, 6500, 9000)
steps - lag(steps)
# NA 900 -1600 2500

The first change is unknown because no previous value exists. For a table, arrange by time and calculate within each person or site:

readings |>
  arrange(site, day) |>
  mutate(change = value - lag(value), .by = site)

consecutive_id(c("a", "a", "b", "b", "a")) gives 1 1 2 2 3. The final "a" begins a new run even though that value appeared earlier. This identifies uninterrupted blocks, not all rows with the same label.

Match summaries to the distribution

For incomes in thousands, c(28, 31, 33, 35, 250) has mean 75.4 and median 33. The extreme income pulls the mean upward. For skewed values such as waiting times, inspect the shape and report the median or both centers.

SummaryWhat it describes
quantile(x, 0.25)A lower-quarter position
IQR(x)Distance between the upper and lower quartiles
sd(x)Spread sensitive to extreme values
range(x)Both endpoints, minimum and maximum

For v <- c(2, 4, 4, 5, 7, 9, 10), the quartiles are 4, 5, and 8, giving IQR 4; the standard deviation is about 2.91 and the range is 2 to 10. The median and IQR resist outliers more than the mean and standard deviation.

Missing input generally makes these summaries missing. With na.rm = TRUE, also report sum(is.na(x)). In summarize(), compute one value per group; in mutate(), keep one value per row. For group values 1 and 3, mutate(share = v / sum(v), .by = g) gives 0.25 and 0.75. first(), last(), and nth(x, 2) select by position, so their meaning also depends on row order.

Key Takeaways

  • Tie rules distinguish min_rank(), dense_rank(), and row_number().
  • Arrange and group before using lag() or lead() to measure changes.
  • Median and IQR resist outliers; mean and standard deviation are sensitive to them.
  • Report missing counts alongside summaries of known values.
2

Clean and reshape text with stringr and regular expressions

Text cleaning has two separate jobs: make the stored values consistent, then find the pieces that carry meaning. stringr handles character-by-character work and pattern matching; tidyr turns packed text into columns or rows. A useful pattern must match the values you want and reject close lookalikes. Looking at real contents, output sizes, and before-and-after counts makes each cleaning decision easier to check.

2.1 Create and combine strings

Strings hold text, including labels, names, and codes that happen to contain digits. Load stringr before using its helpers: library(stringr). Most of its text functions begin with str_; pattern modifiers such as regex(), fixed(), and coll() do not.

Write the characters you mean

Put a string between double or single quotes. Double quotes are the usual tidyverse style; single quotes can make embedded double quotes easier to read.

"data"
'She said "hi"'
"She said \"hi\""

The last two lines represent the same text. In a quoted R string, a backslash begins an escape sequence. \" inserts a double quote, \\ a backslash, \n a new line, and \t a tab. A Unicode escape such as "\u00b5" represents "µ".

The console's printed representation shows quotes and escapes so you could write the string again in code. writeLines() and str_view() show its actual contents. For example, "C:\\data\\file.csv" contains single backslashes and has 16 characters. The printed double backslashes are not extra stored characters.

A raw string avoids this escaping layer:

path <- r"(C:\data\file.csv)"
writeLines(path)
# C:\data\file.csv

It begins with r"( and ends with )". This becomes especially useful when text or a regex contains several backslashes.

Join matching pieces into one value per row

str_c() combines corresponding pieces. A single string is recycled across the other inputs:

name <- c("Ana", "Kofi")
str_c("Hello ", name, "!")
# "Hello Ana!" "Hello Kofi!"

The output still has two values, so this kind of operation fits mutate(). If any piece is missing, str_c() returns NA at that position. Choose a fallback deliberately, for example str_c("Hi ", coalesce(name, "there")) after loading dplyr.

str_glue() builds text from a template. Expressions inside braces are evaluated:

n <- c(2, 5)
str_glue("Hello {name}, you have {n} new messages")

The results are "Hello Ana, you have 2 new messages" and "Hello Kofi, you have 5 new messages". Double braces insert literal braces: str_glue("{{name}} is {name}") starts the first result with "{name} is Ana".

Missing values behave differently here. str_glue("Hi {NA}") produces the text "Hi NA", as does paste0("Hi ", NA). A displayed "NA" inside a sentence is ordinary text, so it will not be counted as missing by is.na().

Collapse many rows into one string

str_flatten() joins a whole vector, not corresponding pieces:

str_flatten(c("apples", "pears", "plums"), ", ", last = ", and ")
# "apples, pears, and plums"

For one member list per team, use df |> summarize(members = str_flatten(member, ", "), .by = team). That returns one row per team. Used in mutate(), the same flattened result is repeated on every row in the group. Decide the intended output size before choosing between joining and flattening.

Key Takeaways

  • Quoted R strings use escapes; raw strings keep backslashes literal.
  • writeLines() or str_view() reveals a string’s contents.
  • str_c() and str_glue() combine corresponding values for rowwise text.
  • str_c() propagates missingness; str_glue() can insert the text "NA".
  • str_flatten() reduces a vector to one string.

2.2 Inspect, tidy and split strings

Two labels can look alike while differing in spaces, case, or stored characters. Inspect those differences before grouping values, then split columns according to the structure their text actually has.

Measure, slice, and tidy

str_length(c("data", "naïve", "", NA)) gives 4 5 0 NA. Empty text has length zero; missing text has unknown length. str_sub() extracts positions starting at 1, and negative positions count backward from the end. In "Rotterdam", positions 1 through 3 give "Rot", positions -3 through -1 give "dam", and position 5 onward gives "erdam". A range beyond the end returns available text or an empty string, not an error.

Use str_to_lower(), str_to_upper(), or str_to_title() to standardize case. Case rules depend on language: str_to_upper("istanbul", locale = "tr") gives "İSTANBUL". str_trim() removes outer whitespace; str_squish() also reduces repeated inner whitespace. Thus " New York " becomes "New York" with str_squish().

Identifiers stay text. str_pad(c("7", "42", "123"), width = 3, pad = "0") returns "007", "042", and "123". Turning an ID into a number loses leading zeros.

Check sorting and invisible differences

str_sort() and str_order() use English sorting rules unless you set locale. Base sort() follows the computer's settings. With numeric = TRUE, str_sort(c("item10", "item2", "item1")) places item2 before item10 by reading digit runs as numbers.

The visible text "café" can store "é" as one character or as "e" plus a combining accent. Their lengths are 4 and 5 and exact == can fail; str_equal() compares their Unicode-equivalent forms. Garbled accented letters after import suggest a file encoding problem. guess_encoding() offers candidates; give readr the file's actual encoding with locale(encoding = "latin1") for a Latin-1 file. Changing case does not repair a wrong encoding.

Split into columns or rows
library(tidyr)
codes <- tibble::tibble(code = "NL-2026-001")
codes |>
  separate_wider_delim(code, delim = "-",
    names = c("country", "year", "id"))

The three new columns contain "NL", "2026", and "001". They remain text. Convert the year if you need arithmetic, while preserving the ID as text. For fixed positions, separate_wider_position() uses named widths: tibble::tibble(ym = "202612") |> separate_wider_position(ym, widths = c(year = 4, month = 2)) gives "2026" and "12".

Unexpected piece counts normally cause an error. Set too_few = "debug" and too_many = "debug" to inspect diagnostic columns, including whether the value fits and what remains. Then choose a repair that matches the data: too_few = "align_start" fills absent pieces with NA; too_many = "drop" discards extras and "merge" retains them in the last field.

For a list packed into one cell, use separate_longer_delim(). A row with tags "red, blue" becomes two rows when split on ", ". Other columns repeat, so count the resulting rows as tags, not as original observations.

Key Takeaways

  • Whitespace, case, Unicode representation, and file encoding can affect text comparisons.
  • str_sub() uses positions; negative positions count from the end.
  • Keep identifiers as text to preserve leading zeros.
  • Choose wider splitting for fields and longer splitting for repeated values.
  • Inspect unexpected piece counts before dropping or merging text.
  • Set locale rules for language-sensitive case changes and sorting.

2.3 Write regular expression patterns

A regular expression describes text that follows a pattern. Build it from small parts and test both intended matches and close values that should fail.

Separate literal text from pattern symbols

Letters and digits usually match themselves. Matching is case-sensitive, so "an" matches within "banana" but "A" does not match "apple". str_view(x, pattern) highlights matched text for inspection.

A dot . means any single character except a new line. To match a literal dot, the regex needs a backslash before it. An ordinary R string needs a second backslash to store that first one:

str_detect(c("3.5", "35"), "\\.")
# TRUE FALSE
str_detect(c("3.5", "35"), fixed("."))
# TRUE FALSE

fixed() treats the pattern as literal text, so no regex escaping is needed. To match a literal backslash with regex, type "\\\\", or use the raw string r"(\\)".

Specify how many characters to match
Pattern partMeaning
?Zero or one of the previous item
+One or more
*Zero or more
{n}Exactly n
{n,}At least n
{n,m}From n through m

For example, "ab+" matches "ab" and "abb", while "ab*" can also match "a". Quantifiers apply to the immediately preceding character, class, or group. Parentheses let a quantifier act on a whole group.

Quantifiers are greedy: they take as much as they can. In "<b>bold</b> and <b>more</b>", "<b>.*</b>" matches from the first opening tag to the last closing tag. Adding ? after the quantifier makes it lazy: "<b>.*?</b>" finds each bold section separately.

Choose a set and a position

A character class matches one character from a set. [aeiou] matches a lowercase vowel, [^aeiou] a character outside that set, and [0-9] a digit. Useful shortcuts are \d for digits, \s for whitespace, and \w for letters, digits, or underscores; uppercase \D, \S, and \W reverse these sets. Ordinary R strings spell them "\\d", "\\s", and "\\w".

Anchors match positions: ^ marks the start and $ the end. "a$" matches "banana"; "^p" matches "pear". The R pattern "\\bapple\\b" uses word boundaries, so it matches "apple pie" but not "pineapple". The stricter "^apple$" matches only the complete string "apple".

Group alternatives and validate a whole field

Alternation means "or". "gr(e|a)y" and "gr[ea]y" both allow "grey" or "gray". Keep shared parts outside the group.

pattern <- "^[A-Z]{2}-\\d{4}$"
str_detect(c("AB-1234", "XAB-1234", "AB-123"), pattern)
# TRUE FALSE FALSE

The anchors require the entire field to be two capitals, a hyphen, and four digits. Without them, a valid-looking piece inside "XAB-1234" would match. Start with a literal piece, add the class and count, then add anchors when checking the whole value. Simple email patterns can flag unusual text for review, but their matches do not establish that an address works.

Key Takeaways

  • Regex symbols describe patterns; fixed() searches literal text.
  • Ordinary R strings add an escaping layer; raw strings remove that layer.
  • Quantifiers control repetition and are greedy unless made lazy.
  • Classes select characters; anchors and word boundaries select positions.
  • Group alternatives and anchor patterns that must match a complete field.

2.4 Detect, count, replace and extract patterns

The same pattern can answer several questions: whether text matches, how often it matches, or which part should be retained or changed. Choose the function by the output you need.

Detect rows and count occurrences

str_detect() returns one logical answer per string. You can filter on it or summarize it:

library(dplyr)
library(stringr)
x <- c("data", "Date", "update", "dated", "mandate")
str_detect(x, "dat")
# TRUE FALSE TRUE TRUE TRUE
mean(str_detect(x, "dat"))
# 0.8

The capital D in "Date" prevents a case-sensitive match. A missing string returns NA, so apply the missing-value choices used for other logical vectors. str_count() instead returns the number of matches in each string. str_count("banana", "a") is 3. Matches do not overlap: str_count("aaa", "aa") is 1.

Change the first match or every match

str_replace() changes only the first match; str_replace_all() changes all matches. Replacing hyphens with slashes in "2026-11-05" gives "2026/11-05" or "2026/11/05", respectively. str_remove() and str_remove_all() use an empty replacement. For example, str_remove_all("+31 (20) 555-0123", "\\D") keeps only digits: "31205550123".

Parentheses capture pieces that a replacement can reuse:

str_replace("2026-11-05",
  "(\\d{4})-(\\d{2})-(\\d{2})", "\\3/\\2/\\1")
# "05/11/2026"

The three groups store year, month, and day. The replacement places group 3 first, then group 2, then group 1. These are backreferences, not ordinary digits. That result is formatted text; use a date parser when you need a date object.

Extract useful pieces

str_extract() returns the first matched substring, or NA if none exists. With "\\d+", the strings "Order 1250 shipped", "No number", and "Codes 12 and 34" yield "1250", NA, and "12". str_extract_all() keeps all matches as a list, so the last string yields both "12" and "34".

To turn structured text into named columns, use tidyr:

tibble::tibble(x = "Ana: 87") |>
  tidyr::separate_wider_regex(x,
    patterns = c(name = "[A-Za-z]+", ": ", score = "\\d+")) |>
  mutate(score = as.integer(score))

Named patterns become columns; the unnamed separator is matched and discarded. The extracted score starts as text. A value such as "Kofi 92" fails because the expected separator is absent; too_few = "debug" helps inspect failures.

Set matching rules and inspect the change

Wrap the pattern in regex("apple", ignore_case = TRUE) for case-insensitive matching. Use fixed("a.b") for the literal characters, or coll() for comparison using language rules. The modifier wraps the pattern, not the searched vector.

Before cleaning, count distinct values. Test the pattern, apply the change, and count again. For measurements, check the unit before discarding text: str_detect(x, regex("kg$", ignore_case = TRUE)) accepts kilogram suffixes. A value in another unit needs conversion before its number can be combined with kilograms.

Key Takeaways

  • str_detect() returns logical answers; str_count() returns nonoverlapping match counts.
  • Choose first-match or all-match replacement explicitly.
  • Capture groups and backreferences let you rearrange matched text.
  • str_extract() returns text; convert extracted numbers before arithmetic.
  • Use pattern modifiers for case, literal text, or language rules.
  • Inspect values before and after cleaning, including their units.
3

Recode categorical data with factors and forcats

A categorical column has possible labels as well as observed rows. Factors store those labels in a deliberate order, which tables and plots can reuse. forcats helps you choose that order, repair labels, and combine small categories. Keeping those operations separate makes it easier to see whether you changed a display, a category’s meaning, or the treatment of missing and unused values.

3.1 Create factors with the right levels

A factor represents a categorical variable with a known set of possible values, called levels. Examples include rating choices, product types, and months. Names and open-ended comments usually stay as character text.

Set the allowed values and their order

A factor stores integer codes pointing to text levels. levels() lists those labels in order and nlevels() counts them. Order matters even when the levels are ordinary words.

month_levels <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun",
                  "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
x <- factor(c("Dec", "Apr", "Jan"), levels = month_levels)
sort(x)
# Jan Apr Dec

Sorting the original text would give "Apr", "Dec", "Jan" alphabetically. A factor lets tables and plots follow the calendar instead. Unobserved months still remain possible levels.

Without explicit levels, base factor() sorts levels alphabetically. forcats' fct() keeps their order of first appearance. For c("medium", "low", "high", "low"), those defaults are high, low, medium and medium, low, high. Neither supplies the intended low-to-high scale; set it explicitly.

Catch values that do not belong
rating_levels <- c("low", "medium", "high")
factor(c("low", "hgh"), levels = rating_levels)
# low <NA>

Base factor() silently turns an unrecognized value into NA. The typo "hgh" then looks like missing data. forcats::fct(c("low", "hgh"), levels = rating_levels) stops with an error instead, making the unexpected value visible before you proceed. Correct the label or revise the allowed set based on the data's meaning.

readr can create factors during import: read_csv(file, col_types = cols(rating = col_factor(rating_levels))). The column then carries the intended levels into later tables and charts. Inspect parsing problems and counts after import.

Distinguish display order from a ranked scale

Every factor has a level order. An ordered factor also declares that the categories themselves are ranked:

rating <- factor(c("high", "low", "medium"),
                 levels = rating_levels, ordered = TRUE)
rating > "low"
# TRUE FALSE TRUE

It prints levels as low < medium < high and supports comparisons and max(). A plain unordered factor does not support a meaningful > comparison and produces missing results with a warning. ggplot2 also uses an ordered color scale by default for ordered factors. Use this type for a real ordinal scale, not simply because you want nominal labels displayed in a chosen sequence.

Recover numeric labels safely

For ff <- factor(c("10", "20", "5")), the alphabetical levels are "10", "20", "5". as.numeric(ff) returns 1 2 3, the internal codes. Those codes do not measure the original quantities.

Convert through text: as.numeric(as.character(ff)) gives 10 20 5. readr::parse_number(as.character(ff)) is useful when the labels contain numeric decorations. If the original values are identifiers, keep them as text instead of converting them at all.

Key Takeaways

  • Factors store codes and an ordered set of allowed labels.
  • Set levels explicitly when alphabetical or first-appearance order is wrong.
  • factor() turns unknown labels into NA; fct() catches them with an error.
  • An ordered factor declares a real ranking and permits ordinal comparisons.
  • Convert numeric factor labels through character text to avoid returning codes.

3.2 Reorder factor levels for tables and plots

Level order shapes a table, an axis, or a legend. Choose an order that helps the reader compare the categories while keeping any genuine rating scale intact.

Order categories by a measured value

fct_reorder(f, x) sorts the levels of f using a summary of x. Its default summary is the median.

library(dplyr)
library(forcats)
tv <- tibble::tibble(
  genre = c("Drama", "Drama", "Comedy", "News", "News", "News", "Sport"),
  hours = c(3, 5, 2, 1, 1.5, 2.5, 6)
)
tv <- tv |> mutate(genre = fct_reorder(genre, hours))
levels(tv$genre)
# "News" "Comedy" "Drama" "Sport"

The category medians are 1.5, 2, 4, and 6 in that order. Reordering changes level order, not a row's genre or hours. To order by means, supply .fun = mean; to reverse the summary-based order, add .desc = TRUE.

In a boxplot, ggplot(tv, aes(x = hours, y = fct_reorder(genre, hours))) + geom_boxplot() places related values together by their typical size. When several later outputs need the same order, store the changed factor with mutate() as above.

Order by frequency

fct_infreq() sorts from most to least frequent. In these data, News has three rows, Drama two, and Comedy and Sport one each. Frequency ties retain their previous level order. Frequency answers "how many rows?"; it does not answer "how many hours?" A category with many small readings can be most frequent but have a low median.

fct_rev() reverses the current order. On a horizontal ggplot2 axis, the first level appears at the bottom. Using fct_rev(fct_infreq(genre)) on that axis puts the most frequent category at the top. Check the plotted direction as well as levels().

Preserve a natural scale or set an order by hand

Nominal labels such as genres have no intrinsic ranking, so a summary or frequency order can aid comparison. Ordinal labels such as Disagree, Neutral, Agree already form a scale. Sorting them by popularity would hide that scale.

fct_relevel() moves named levels by hand. For levels "Not applicable", "Disagree", "Neutral", and "Agree", use:

answers <- factor(c("Agree", "Neutral"),
  levels = c("Not applicable", "Disagree", "Neutral", "Agree"))
levels(fct_relevel(answers, "Not applicable", after = Inf))
# "Disagree" "Neutral" "Agree" "Not applicable"

By default, named levels move to the front; after = Inf moves them to the end. This lets you retain a meaningful response scale and place a separate response outside it.

Match a line legend to the line endings

fct_reorder2(f, x, y) orders categories using the y values at the largest x values. For a time-based line chart, this aligns legend order with the lines' positions at the right edge. The reader can match colors to endings more easily.

Inspect both levels(f) and a count table after reordering. The first checks the sequence; the second checks that the observations still belong to the intended categories.

Key Takeaways

  • fct_reorder() sorts levels by a summary, using the median by default.
  • fct_infreq() sorts by row frequency; fct_rev() reverses an order.
  • Keep ordinal response scales in their natural sequence.
  • fct_relevel() places chosen labels manually; fct_reorder2() helps line legends.

3.3 Rename, combine and lump factor levels

Category cleaning can rename one label, merge several meanings, or group rare values for a clearer display. Check which change you intend before applying a forcats function.

Rename and merge labels

fct_recode() puts the new label on the left and the old label on the right:

library(forcats)
pt <- factor(c("car", "car", "car", "bus", "bus", "bike", "tram", "walk"))
fct_recode(pt, "bicycle" = "bike")

Only "bike" changes. Giving two old labels the same new name merges them: fct_recode(pt, "public transport" = "bus", "public transport" = "tram"). Other labels stay as they are. A misspelled old name, such as "bikes", produces a warning and leaves those values unchanged. Read the warning and inspect levels() or counts.

For several grouped labels, fct_collapse() takes a vector on the right:

fct_collapse(pt,
  "public transport" = c("bus", "tram"),
  "active" = c("bike", "walk")
)

The result has active, public transport, and car categories. This is a change in how categories are grouped, so the new labels should describe the combined meanings accurately.

Group rare levels using a stated rule

Lumping combines small categories in an "Other" level. For the eight trips above, fct_lump_n(pt, n = 2) keeps car and bus, producing counts car 3, bus 2, Other 3. Set other_level = "Other modes" for a more descriptive label.

FunctionRule for keeping levels
fct_lump_n(f, n)The n most frequent, including boundary ties
fct_lump_prop(f, prop)Shares greater than prop
fct_lump_min(f, min)Counts at least min
fct_other(f, keep = ...)The labels you name

fct_lump_lowfreq() groups the rarest levels while keeping the combined "Other" group smaller than the retained groups. These rules serve different purposes. Use a count threshold when a minimum sample size matters, a proportion threshold when relative size matters, and fct_other() when membership is a deliberate choice.

Ties can make fct_lump_n() keep more than n levels. If a and b each occur twice and c and d once, requesting n = 1 keeps both a and b. Count the result instead of assuming a fixed number of retained labels.

Separate missing from unused

An NA is a missing observation; it is not a factor level by default. fct_na_value_to_level(f, level = "(missing)") turns it into a named category that can be displayed and ordered. This records missingness as a category; it does not recover an unknown answer.

An unused level is different: the label is allowed but currently has no rows. Filtering out all walking trips leaves "walk" in the factor's levels. fct_drop() removes such unused levels. If the empty category is meaningful, retain it and use count(df, mode, .drop = FALSE) to display its count of zero. Dropping a level changes the allowed label set, not the number of observed trips.

Key Takeaways

  • fct_recode() uses new names on the left and old labels on the right.
  • fct_collapse() combines named sets of existing levels.
  • Lumping rules differ by count, proportion, rank, or chosen labels.
  • Boundary ties can retain more than n levels in fct_lump_n().
  • A missing-value level labels unknown observations; an unused level has no observations.
  • Use fct_drop() to remove unused levels or .drop = FALSE to report them.
4

Work with dates and times using lubridate

A date, a clock time, and an instant answer different questions. Parsing makes those meanings explicit, while components and rounded dates help group observations. Time arithmetic adds a further distinction: elapsed seconds and calendar steps can disagree around month ends and daylight saving changes. Choosing the type, source format, and time zone first keeps later comparisons and summaries meaningful.

4.1 Create dates and date-times from data

Choose a time type by what was recorded. A date identifies a day; a time of day identifies a clock reading; a date-time identifies an instant with both a date and a clock time.

Choose the simplest useful type

Tibbles display dates as <date> (class Date), times as <time> (commonly class hms), and date-times as <dttm> (class POSIXct). Use a date for a delivery day when its hour does not matter. Use a date-time for an event that must be placed on a shared timeline. lubridate::today() gets the current date, while now() gets the current date-time.

An ISO 8601 date uses year-month-day, such as "2026-11-05". Putting the largest component first makes the order clear. A date-time adds the time, as in "2026-11-05 14:30:00". readr recognizes ISO-style date and date-time columns during CSV import; a value such as "05/11/2026" needs an explicit parsing decision.

Match the parser to the source order

lubridate names its helpers by component order:

library(lubridate)
ymd("2026-11-05")
mdy("November 5th, 2026")
dmy("5 Nov 2026")
ymd(20261105)
# Each represents 2026-11-05

For date-times, use helpers such as ymd_hms() or ymd_hm(). They use UTC unless a zone is supplied. ymd_hms("2026-11-05 14:30:00", tz = "Asia/Tokyo") records that clock reading in Tokyo.

The text "03/04/2026" can mean April 3 or March 4. dmy() and mdy() can both parse it successfully, so a lack of warnings cannot settle the intended meaning. Read the source documentation or look for decisive values such as "25/12/2026", which cannot be month-first.

Supply an exact format when needed

readr uses format codes for known layouts:

readr::parse_date("05.11.2026", format = "%d.%m.%Y")
# 2026-11-05

%Y is a four-digit year, %m a month number, and %d a day number. %B and %b read full and abbreviated month names; %H, %M, and %S describe hours, minutes, and seconds. During import, col_types = cols(day = col_date("%d/%m/%Y")) applies the same idea to a column.

Impossible dates become missing with a warning. ymd(c("2026-02-28", "2026-02-30")) gives a valid date and NA. Compare missing counts before and after parsing and inspect the original failed strings; a new NA is evidence of a parsing problem to investigate.

Build values from columns and convert types

Use make_date(year, month, day) for separate date components. make_datetime(2026, 11, 5, 14, 30) produces 2026-11-05 14:30:00 UTC. Inside mutate(), column names can supply each component vector.

as_date() extracts a date from a date-time; as_datetime() creates a date-time. Numeric inputs use the Unix epoch, 1970-01-01, but their units differ: as_date(365) counts days and gives 1971-01-01, while as_datetime(36000) counts seconds and gives 1970-01-01 10:00:00 UTC.

Key Takeaways

  • Use dates for days, times for clock readings, and date-times for instants.
  • Choose a parser from the source’s component order, not from a successful guess.
  • Count new missing values after parsing and inspect failures.
  • make_date() and make_datetime() build values from separate components.
  • Numeric date and date-time conversions count days and seconds from the epoch, respectively.

4.2 Extract, round and update date components

Once a column contains real dates or date-times, you can extract parts, group nearby events, or update a component. Each operation serves a different purpose.

Extract the component you need
library(lubridate)
d <- ymd_hms("2026-11-05 14:30:59")
year(d)    # 2026
month(d)   # 11
mday(d)    # 5
yday(d)    # 309
hour(d)    # 14
minute(d)  # 30
second(d)  # 59

mday() is the day within the month; yday() is the day within the year. Leap years change the latter: December 31 is day 365 in 2026 and day 366 in 2028. A day-of-year value alone does not identify a calendar date across different years.

month(d, label = TRUE) gives an ordered factor labeled "Nov". Add abbr = FALSE for "November". Labels follow the computer's language settings unless you supply locale. Their factor order follows the calendar, avoiding alphabetical month order in a chart.

Weekday numbers also need a convention. wday() starts on Sunday by default, so Thursday 2026-11-05 is 5 and Sunday 2026-11-08 is 1. With week_start = 1, Monday is the first day, so those results become 4 and 7. Set this argument deliberately when comparing weekdays or defining weeks.

Round to make grouping periods

floor_date() rounds down, round_date() rounds to the nearest boundary, and ceiling_date() rounds up. For d, flooring to "month" gives midnight at 2026-11-01; rounding to "hour" gives 15:00:00 because the time is just past halfway through the hour.

floor_date(d, "week")
# Week starts on Sunday 2026-11-01
floor_date(d, "week", week_start = 1)
# Week starts on Monday 2026-11-02

Use rounded dates as grouping keys. For events on November 2, 4, 8, 9, and 12, Monday-based weekly grouping produces three events in the week of November 2 and two in the week of November 9. A pipeline can express this as logs |> count(week = floor_date(t, "week", week_start = 1)). The grouping value retains its date, which keeps separate years apart and works on a time axis.

Update with attention to month ends

update() sets chosen components and keeps the rest. update(ymd("2026-11-05"), year = 2030, month = 2) gives 2030-02-05. For the date-time d, update(d, hour = 8, minute = 0, second = 0) sets its clock to 08:00:00 on the same day. Assignment such as month(x) <- 12 can also change a component.

A component change can roll beyond the requested month. update(ymd("2026-01-31"), month = 2) gives 2026-03-03: February has no day 31, so the three excess days carry into March. Inspect end-of-month results instead of treating a successful update as confirmation of the intended date.

For a numeric time-of-day axis, hour(d) + minute(d) / 60 gives 14.5 for 14:30, ignoring seconds. When clock formatting is useful, hms::as_hms("14:30:00") keeps a standalone time-of-day value.

Key Takeaways

  • Accessors extract components; month and weekday labels can be ordered factors.
  • Set week_start to match the intended weekday numbering and weekly groups.
  • Rounded dates make useful period keys that retain the year.
  • Component updates can roll invalid dates into the next month.

4.3 Calculate with time spans and time zones

"One day later" can mean 86,400 seconds later or the same clock time tomorrow. Those meanings can differ. Pick the time span that matches the question before adding or subtracting it.

Elapsed time, calendar steps, and anchored spans
TypeMeaningExample
DurationExact secondsdhours(36)
PeriodCalendar or clock unitsmonths(1)
IntervalFixed start and endstart %--% end

Subtracting dates gives a difftime. From 2026-11-05 to 2026-12-25, the difference is 50 days. as.numeric(x, units = "weeks") expresses that difference as about 7.142857 weeks; as.duration(x) expresses it in seconds.

Duration constructors start with d: ddays(1) is 86,400 seconds, dweeks(1) is 604,800, and dyears(1) is 31,557,600, or 365.25 days. Use them for elapsed time, such as a 36-hour experiment. Periods such as days(1), weeks(2), and years(1) move along calendar or clock units.

Follow a daylight saving change

Amsterdam moved its clocks forward on March 29, 2026. Starting at 13:00 on the previous day:

library(lubridate)
t0 <- ymd_hms("2026-03-28 13:00:00", tz = "Europe/Amsterdam")
t0 + ddays(1) # 2026-03-29 14:00:00 CEST
t0 + days(1)  # 2026-03-29 13:00:00 CEST

The duration preserves 24 elapsed hours. The period preserves the local clock time on the next day, only 23 elapsed hours away. Across leap years, a duration year and a calendar year can also differ: from 2028-01-01, dyears(1) reaches 2028-12-31 06:00:00, while years(1) reaches 2029-01-01.

Periods still need a valid destination. ymd("2026-01-31") + months(1) is NA because February 31 does not exist. ymd("2026-01-31") %m+% months(1) rolls back to February 28; in 2028 it reaches February 29. %m-% applies the rollback rule when subtracting months. A period does not guarantee a valid leap-day anniversary in a non-leap year.

Use endpoints for calendar lengths
iv <- ymd("2026-11-05") %--% ymd("2027-02-14")
iv / days(1)       # 101
iv %/% months(1)   # 3
as.period(iv)     # 3 months and 9 days

An interval's endpoints make actual calendar lengths available. Whole years of age can be calculated with (birth_date %--% reference_date) %/% years(1). %within% tests whether a date lies in an interval; int_overlaps() tests whether two intervals overlap.

Convert a display or repair a recorded zone

Use IANA zone names such as "Asia/Tokyo", "Europe/London", and "America/Sao_Paulo". Abbreviations can be ambiguous. OlsonNames() lists available names and Sys.timezone() reports the computer's zone. UTC has no daylight saving change.

For 2026-11-05 09:00 in Tokyo, with_tz(x, "Europe/London") shows 00:00 on November 5: the instant stays fixed. In São Paulo it shows 21:00 on November 4. force_tz(x, "Europe/London") keeps 09:00 and changes the instant by nine hours. Use that operation to repair a clock reading assigned the wrong zone, not to display an event elsewhere.

Key Takeaways

  • Durations measure fixed seconds; periods move in calendar or clock units.
  • Intervals attach a span to a definite start and end.
  • Daylight saving and leap years can separate elapsed time from calendar time.
  • Use %m+% or %m-% when month arithmetic should roll back to a valid month end.
  • with_tz() preserves the instant; force_tz() preserves the clock reading.
  • Use IANA zone names and inspect dates as well as clock times after conversion.
5

Treat missing values deliberately

Missing data includes visible NA cells and observations with no row at all. Those two forms require different checks. Counting missing cells shows what is unknown among recorded rows; completing expected combinations reveals gaps that summaries cannot see. Filling, keeping, or dropping a gap changes the population described by a result, so the choice belongs with the analysis and should be reported with it.

5.1 Find and handle explicit missing values

An explicit missing value occupies a cell as NA. It means the value is unknown, not that it equals zero. Count missing values before choosing how to handle them.

Find missing cells and distinguish calculation failures
x <- c(12, NA, 7, 20, NA)
sum(is.na(x))  # 2
mean(is.na(x)) # 0.4

The count is two and the share is 40%. For a whole data frame, colSums(is.na(df)) counts missing cells by column. Use is.na() instead of x == NA, which returns unknown comparisons.

Most operations involving unknown values stay unknown: NA + 1 and NA > 1 give NA. Some results are settled regardless of the missing value, such as NA ^ 0, which is 1, NA | TRUE, which is TRUE, and NA & FALSE, which is FALSE.

NaN means "not a number" and can signal a calculation without a numeric result, such as 0/0 or mean(numeric(0)). 1/0 gives Inf instead. is.na() detects both NA and NaN; is.nan() identifies only NaN. In a group summary, investigate NaN as a possible sign that no usable values remained.

Convert documented placeholders

A dataset may encode missingness as -99, 999, or empty text. Those codes distort summaries if treated as measurements. readr treats empty cells and "NA" as missing by default; extend its na argument when the file documentation gives other codes.

library(dplyr)
x <- c(15, -99, 22, 999, 18)
x <- na_if(x, -99) |> na_if(999)
# 15 NA 22 NA 18

Only convert a code when it means missing in that column. The number 999 could be a genuine value elsewhere.

Fill or replace for a specific reason

tidyr::fill() carries a known value down into later missing cells. In a label column where blanks mean "same as above", "Amara", NA, NA, "Jonas" becomes Amara, Amara, Amara, Jonas. .direction = "up" fills from below. Arrange rows and keep separate people or sites grouped so that values do not cross unrelated boundaries.

coalesce() chooses the first non-missing value at each position. coalesce(c(NA, 2, NA), c(1, NA, NA), 0) returns 1 2 0. A zero fallback is appropriate for a known absence, such as no sales in a complete log. It changes an unknown measurement into invented data if its value is not known. For c(4, NA, 6), the known-value mean is 5; replacing NA with zero gives about 3.33.

Drop rows and summarize consciously

drop_na(df, score) drops rows missing score; drop_na(df) checks every column. Compare row counts before and after. A missing note should not remove a valid score when the analysis only requires scores. Missingness related to an outcome can also bias the retained sample.

filter() keeps only definite true conditions. With values 3, NA, and 8, filtering v > 5 keeps 8, while filtering !(v > 5) keeps 3. The missing row appears in neither result. Add | is.na(v) if it should remain.

sum(x, na.rm = TRUE) totals known values only. For the original readings it is 39; unknown contributions have not been recovered. Report how many cells were missing, what you did, and which observations the resulting statistic describes.

Key Takeaways

  • Count missing cells with is.na() before cleaning.
  • NaN signals a numeric calculation without a numeric result; it is also detected by is.na().
  • Convert documented placeholder codes with import settings or na_if().
  • Use fill() for repeated labels and coalesce() for justified alternatives.
  • Dropping rows or replacing unknown values can change or bias a result.
  • na.rm = TRUE describes known data; report its missing count and denominator.

5.2 Reveal implicit missing values and empty groups

Some missing values have no cell to inspect. An implicit missing value is an expected observation whose whole row is absent. You need the expected combinations to reveal it.

Compare recorded rows with expected rows

Suppose store A has rows for quarters 1 through 4, with NA units in quarter 2. Store B has rows for quarters 1, 2, and 4. There are seven rows, but eight store-quarter combinations. A's quarter 2 is explicitly missing; B's quarter 3 is implicitly missing.

pivot_wider(sales, names_from = qtr, values_from = units) makes one cell for each represented store-quarter combination. The absent B quarter 3 becomes NA, visible alongside A's existing missing cell. Reshaping reveals the gap without deciding its value.

Add absent combinations

complete() adds missing rows:

library(tidyr)
sales |> complete(store, qtr = 1:4)

The result has eight rows. Naming the full quarter set matters if a quarter is absent everywhere; observed values alone cannot tell R that an unseen quarter should exist. For a regular numeric sequence, full_seq(c(1, 2, 4, 7), 1) supplies every integer from 1 through 7.

Decide whether absence means zero

A complete visit log records 5, 3, 6, and 2 visits on days 1, 2, 4, and 7. Its documentation says an absent day means nobody visited. Complete the days and fill the new counts:

visits <- tibble::tibble(day = c(1, 2, 4, 7), n = c(5, 3, 6, 2))
visits |> complete(day = full_seq(day, 1), fill = list(n = 0))

The four recorded counts average 4. Including the zero-visit days gives 16 divided by 7, about 2.29 visits per day. Those summaries describe different sets of days. If an absent day instead means a sensor was offline, leave its reading as NA.

By default, complete(..., fill = list(n = 0)) also fills pre-existing missing counts. If existing NA cells mean unknown but only newly added rows mean zero, add explicit = FALSE. That keeps the two meanings separate while revealing the missing combinations.

Show empty categories honestly

A factor can list categories that have no observed rows. If member has levels "yes" and "no" but only "no" responses, count(df, member) omits the empty level. count(df, member, .drop = FALSE) includes "yes" with count zero. In a ggplot2 chart, scale_x_discrete(drop = FALSE) keeps its axis position.

A group with zero rows has no observed measurements. After group_by(member, .drop = FALSE), its n() is 0, its mean is NaN, its minimum is Inf, and its maximum is -Inf; the extrema warn. These are empty-input results, not measured quantities. Report "no data" for the summary while retaining the count of zero.

Include both kinds of missingness in the report: missing cells among recorded rows, absent expected observations, and the filling or dropping choices. This lets readers tell a genuinely observed zero from an unknown value or an empty group.

Key Takeaways

  • Explicit missingness is an NA cell; implicit missingness is an absent expected row.
  • pivot_wider() and complete() reveal missing combinations.
  • Supply the expected value set when values are absent everywhere.
  • Fill absent counts with zero only when the recording process makes absence mean zero.
  • explicit = FALSE limits complete() filling to newly added rows.
  • Keep empty factor groups when useful, and describe their summaries as having no data.
  • Report missingness and the observation set behind each result.

Strings and Factors in R examples

5 Walkthroughs

1

Turn readings into conditions, labels, and changes

18 steps
Follow a short measurement example from logical comparisons to counts, numeric transformations, and ordered changes.
  1. 1
    IntroductionChoose what each result should describe

    A monitoring table contains one temperature per observation. Some temperatures are missing, and later you will compare readings within a site.

    A row label, a count of warm readings, and a change from the previous reading need different operations. Start with the elementwise condition, then decide whether to keep one result per row or reduce the results to a summary. Load dplyr for the examples.

  2. 2
    ExampleRead a condition position by position
    temp <- c(16, 27, NA, 23)
    temp > 22
    # FALSE TRUE NA TRUE
    

    The condition produces four answers, in the original order. The missing third reading cannot be declared above or below the threshold.

    Use is.na(temp) to locate that missing position. temp == NA cannot find it: comparing any value with an unknown value produces an unknown answer.

  3. 3
    ExplanationBuild a range from two complete comparisons

    To keep temperatures above 20 °C and at most 25 °C, write temp > 20 & temp <= 25. Both comparisons apply to each position.

    For a choice between listed values, use temp %in% c(16, 23). The expression temp == 16 | 23 is wrong: its bare nonzero number counts as true, making every answer true. The vector forms & and | belong in column operations; scalar && and || expect single values.

  4. 4
    ChallengeCan an unknown side change the answer?

    What are TRUE | NA and TRUE & NA, and why do they differ?

    ---reveal---

    The first is TRUE: an or condition is already satisfied by its known true side. The second is NA: an and condition still needs the unknown side to be true. Missingness does not always spread mechanically; the condition's logic determines whether the unknown value matters.

  5. 5
    TipCheck decimal equality with a tolerance

    Calculated decimals are stored in binary, so exact equality can fail after arithmetic. 0.1 + 0.2 == 0.3 is false, while near(0.1 + 0.2, 0.3) is true.

    Use == for an exact equality test and near() when comparing calculated decimals. Equality needs two equals signs: in a dplyr call, a single = names an input instead of expressing the intended comparison.

  6. 6
    ExampleCount known warm readings
    sum(temp > 22, na.rm = TRUE)
    # 2
    mean(temp > 22, na.rm = TRUE)
    # 0.6666667
    

    True contributes 1 and false contributes 0. Removing the missing comparison leaves three known readings, of which two exceed 22 °C.

    Report "two of three known readings." The original vector has four positions, but its missing condition is absent from this mean's denominator.

  7. 7
    ExplanationChoose labels without hiding unknowns
    if_else(temp > 22, "warm", "cool", missing = "unknown")
    # "cool" "warm" "unknown" "warm"
    

    The two outcome labels are compatible text values. Mixing text with a numeric outcome causes a type error.

    any(temp > 22) is true because a known warm reading settles it. all(temp > 22) is false because the known 16 °C reading fails; the missing reading cannot undo that failure.

  8. 8
    ExampleRead the first matching rule
    case_when(
      is.na(temp) ~ "unknown",
      temp >= 25 ~ "hot",
      temp > 20 ~ "mild",
      .default = "cool"
    )
    # "cool" "hot" "unknown" "mild"
    

    The first true rule wins for each element. The specific hot threshold precedes the broader mild threshold. The missingness rule stops the unknown reading from falling through to a misleading cool default.

  9. 9
    ChallengeKeep missing rows deliberately

    A table column contains the four temperatures above. Does filter(df, temp > 22) keep the missing row? What condition would keep it too?

    ---reveal---

    It keeps only 27 and 23. Use temp > 22 | is.na(temp) to retain the missing row explicitly. Base vector subsetting behaves differently: temp[temp > 22] keeps an NA placeholder for the unknown comparison.

  10. 10
    ExampleParse the number and retain its meaning
    readr::parse_number(c("18 kg", "62%"))
    # 18 62
    

    Parsing removes the surrounding text but does not convert units or percentages. The second number needs division by 100 if the desired value is the proportion 0.62.

    For data using decimal commas, supply readr's locale settings. The input text can use a comma decimal mark while R numeric code continues to use a point.

  11. 11
    ExplanationLimit each reading separately
    pmin(c(3, 14, 9), 10)
    # 3 10 9
    min(c(3, 14, 9), 10)
    # 3
    

    pmin() caps each element, preserving three results; min() summarizes everything into one result. pmax(x, 0) similarly puts a zero floor under each value.

    Base arithmetic recycles shorter vectors. Recycling one constant is useful; a repeating pair compares alternating positions, while membership checks each row against the whole set.

  12. 12
    ExampleSeparate whole units from a remainder

    A process takes 158 minutes. 158 %/% 60 gives two whole hours, and 158 %% 60 gives 38 minutes left over.

    The operators split one quantity into whole units and a remainder. They do not parse a decimal clock reading. For a separate clock code such as 0915 stored numerically as 915, dividing by 100 gives hour 9 and remainder 15, because the last two digits encode minutes.

  13. 13
    ChallengeCheck a bin boundary

    With cut(x, breaks = c(0, 10, 30)), where does 10 go? What changes with right = FALSE?

    ---reveal---

    The default assigns 10 to (0,10], the lower interval, because its upper endpoint is included. With right = FALSE, 10 belongs to [10,30). The default intervals exclude zero; the first lower-inclusive interval includes it. Check endpoints before giving bins names.

  14. 14
    TipArrange before accumulating

    A running total follows the vector's current order: cumsum(c(4, 6, 3)) is 4 10 13. Arrange time-based rows before computing it.

    Rounding also needs a chosen rule. round() rounds exact halfway values to even; floor() moves toward smaller integers, so floor(-1.8) is -2. To round to a fixed increment, divide by that increment, round, and multiply back.

  15. 15
    ExampleChoose how tied positions should behave
    x <- c(4, 9, 9, 15)
    min_rank(x)   # 1 2 2 4
    dense_rank(x) # 1 2 2 3
    row_number(x)# 1 2 3 4
    

    The first two methods give equal values equal ranks; only min_rank() leaves a gap. row_number() breaks ties by order. Use desc(x) for largest-first ranking. A rank cutoff includes every tie at its boundary, so the number of selected rows can exceed the cutoff.

  16. 16
    ExampleMeasure change within each site
    readings |>
      arrange(site, day) |>
      mutate(change = value - lag(value), .by = site)
    

    Arranging puts each site's observations in time order, while grouping restarts the lag for each site. For readings 7, 12, and 10, the changes are NA 5 -2.

    The first change is unknown because no previous observation exists in that site's data.

  17. 17
    ChallengeCombine selection with a summary

    Scores are 50, 70, 70, and 90. After retaining descending min_rank() values at most 2, how many scores remain and what is their median?

    ---reveal---

    The ranks are 4, 2, 2, and 1, so three scores remain: 70, 70, and 90. Their median is 70. A top-two rank rule preserves the second-place tie; taking only two rows would answer a different selection request.

  18. 18
    RecapMake the output auditable

    For a condition-based result, inspect a passing case, a failing case, and a missing case. Check whether a count or proportion describes all observations or only known ones.

    For a sequence-based result, inspect row order and group boundaries. For a distribution, choose a center and spread suited to its shape: median with IQR for resistance to extremes, or mean with standard deviation when that sensitivity is useful.

2

Clean text and build a code checker

20 steps
Inspect stored characters, split structured values, and develop a regex that distinguishes valid codes from close failures.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionRead text before changing it
  2. 2
    ExplanationSeparate stored text from its printed form
  3. 3
    ExampleCreate one label per row
  4. 4
    ChallengeChoose row labels or a group list
  5. 5
    TipDo not confuse missing text with the letters NA
  6. 6
    ExampleClean a label and preserve its code
  7. 7
    ExplanationInspect length and character positions
  8. 8
    ExampleSplit fields into columns
  9. 9
    ChallengeSplit several items without creating several fields
  10. 10
    Key InsightLookalike text can still differ
  11. 11
    ExampleStart with the characters a code allows
  12. 12
    ExampleRequire the whole value to match
  13. 13
    ExplanationEscape punctuation at both layers
  14. 14
    ChallengeGroup the choice before anchoring it
  15. 15
    ExplanationChoose how repetition should stop
  16. 16
    ExampleChoose a detection or a count
  17. 17
    ExampleExtract first, then convert the type
  18. 18
    ExampleReuse captured pieces in a replacement
  19. 19
    ChallengeKeep a unit check attached to its number
  20. 20
    RecapInspect the shape and meaning of the result
3

Make category labels and displays reliable

14 steps
Build factors, order them for a useful display, and distinguish recoded labels from missing values and unused levels.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionKeep categories and observations separate
  2. 2
    ExampleDeclare the level set explicitly
  3. 3
    TipSurface unexpected labels early
  4. 4
    ChallengeRead numeric labels without averaging codes
  5. 5
    ExampleOrder nominal groups by their medians
  6. 6
    ExplanationChoose frequency or manual order
  7. 7
    ChallengeMatch the ordering to the question
  8. 8
    ConnectionRead a line legend at the right edge
  9. 9
    ExampleRename a level or merge a set
  10. 10
    ExampleLump with a rule you can explain
  11. 11
    ChallengePredict a tie at the lumping cutoff
  12. 12
    Key InsightA missing value is not an empty level
  13. 13
    ChallengeKeep the empty category in a report
  14. 14
    RecapCheck exactly what a factor operation changed
4

Parse timestamps and choose the right kind of time

17 steps
Move from recorded date text to grouped calendar periods, elapsed times, month ends, and time-zone decisions.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart from what was recorded
  2. 2
    ExplanationChoose a type that matches the information
  3. 3
    ExampleMatch text order to a helper
  4. 4
    ChallengeResolve an ambiguous date from the source
  5. 5
    ExampleBuild from components and inspect failures
  6. 6
    ExampleExtract components for a useful question
  7. 7
    ExampleUse a date as the monthly group key
  8. 8
    ChallengeFind the calendar consequence of an update
  9. 9
    TipChoose a clock representation for plotting
  10. 10
    ExplanationPick seconds or calendar units
  11. 11
    ExampleFollow a clock change one step at a time
  12. 12
    ChallengeChoose a month-end rule
  13. 13
    ExampleAnchor a span to actual endpoints
  14. 14
    ExampleDisplay one event in another zone
  15. 15
    ChallengeRepair a clock assigned the wrong zone
  16. 16
    ChallengeParse first, then measure the requested span
  17. 17
    RecapCheck the meaning at both ends
5

Find hidden gaps without inventing measurements

12 steps
Count missing cells, complete expected observations, and report known zeros separately from unknown values and empty groups.

Save this lesson to follow every Walkthrough step by step.

  1. 1
    IntroductionStart with the recording process
  2. 2
    ExampleCount unknown values before replacing them
  3. 3
    ExampleNormalize a documented placeholder
  4. 4
    ExplanationFill labels only when blanks mean repeat
  5. 5
    ChallengeKeep valid scores despite missing comments
  6. 6
    Key InsightKnown-value totals do not recover unknown contributions
  7. 7
    ExampleLook for a row that never existed
  8. 8
    ExampleComplete the expected combinations
  9. 9
    ChallengeDistinguish a zero day from a damaged count
  10. 10
    ExampleCount empty groups without inventing a mean
  11. 11
    ChallengeChoose the correct daily denominator
  12. 12
    RecapReport the gap and the decision together

Strings and Factors in R practice questions

60 Practice Questions in 6 sets

Set 1: Strings and patterns10 Practice Questions

Question 1 of 10

What does str_c("Batch ", c("H2", "J7")) return?
  1. "Batch H2J7"
  2. c("Batch H2", "Batch J7")
  3. c("Batch ", "H2", "J7")
  4. "Batch H2, Batch J7"
Show answerHide answer
Answer: B
str_c() joins corresponding pieces and recycles the single prefix, producing one result for each code. The vector therefore has two strings. A single collapsed result would require a flattening operation, not this elementwise combination.

Question 2 of 10

For name <- c("Mina", NA), how do str_c("Hi ", name) and str_glue("Hi {name}") differ at the second position?
  1. Both give NA because the name is missing.
  2. Both give "Hi NA" as ordinary text.
  3. str_c() gives "Hi NA"; str_glue() gives NA.
  4. str_c() gives NA; str_glue() gives "Hi NA".
Show answerHide answer
Answer: D
str_c() propagates a missing piece, so its second output is genuinely missing. Glue substitutes the ordinary text "NA" into the template. These outputs may look related when printed, but is.na() distinguishes the missing value from a sentence containing those letters.

Question 3 of 10

What does str_sub(str_squish(" Lima Norte "), -5, -1) return?
  1. "Nort "
  2. "Lima "
  3. "Norte"
  4. "orte "
Show answerHide answer
Answer: C
str_squish() first removes the outer spaces and reduces the internal run to one space, leaving "Lima Norte". Negative positions then select its final five characters, "Norte". Counting from the uncleaned text would incorrectly retain trailing spaces.

Question 4 of 10

What does str_pad("38", width = 5, pad = "0") return?
  1. "00038"
  2. "38000"
  3. "0038"
  4. "0000038"
Show answerHide answer
Answer: A
The requested width is five characters, so three zeros are added before the two-character input. Padding defaults to the left. Adding five zeros would confuse the final width with the number of characters to insert.

Question 5 of 10

What R pattern accepts only a complete value of three capital letters followed by two digits?
  1. "[A-Z]{3}[0-9]{2}"
  2. "^[A-Z]{2}[0-9]{3}$"
  3. "^[A-Z]{3}[0-9]{2}$"
  4. "^[A-Z]+[0-9]+$"
Show answerHide answer
Answer: C
The two quantifiers require exactly three letters and two digits, and the anchors make the whole string follow that layout. Without anchors, a longer value could pass by containing the five-character pattern inside it. The plus quantifier would allow the wrong field lengths.

Question 6 of 10

What does str_detect(c("7.2", "72", "7x2"), fixed(".")) return?
  1. TRUE TRUE TRUE
  2. TRUE FALSE FALSE
  3. TRUE FALSE TRUE
  4. FALSE TRUE FALSE
Show answerHide answer
Answer: B
fixed() treats the dot as literal punctuation, which appears only in "7.2". It does not interpret the dot as a regex wildcard. Making every entry true would apply regex rules even though the pattern modifier explicitly requests literal text.

Question 7 of 10

What does str_replace("2027/08/19", "/", "-") return?
  1. "2027-08-19"
  2. "2027/08-19"
  3. "2027/08/19"
  4. "2027-08/19"
Show answerHide answer
Answer: D
str_replace() changes the first slash in each string and leaves the later slash intact. The all-match form would change both. Replacing the last slash would require a pattern that specifically locates it; the supplied literal slash matches the first occurrence.

Question 8 of 10

What does str_count("abababa", "aba") return?
  1. 2
  2. 1
  3. 3
  4. 4
Show answerHide answer
Answer: A
The first match consumes positions 1 through 3, and the next nonoverlapping match occupies positions 5 through 7. The match starting at position 3 overlaps the first and is not counted. Counting every possible starting position would therefore give a different result.

Question 9 of 10

A field must be exactly two uppercase letters, a literal dot, and one or two digits. What R pattern rejects both "XAB.12" and "ABx12" while accepting "AB.7"?
  1. "[A-Z]{2}\.[0-9]{1,2}"
  2. "^[A-Z]{2}\.[0-9]{1,2}$"
  3. "^[A-Z]{2}.[0-9]{1,2}$"
  4. "^[A-Z]{2}\.[0-9]{2}$"
Show answerHide answer
Answer: B
The anchors enforce the whole field, the escaped dot requires punctuation, and the final quantifier allows one or two digits. An unescaped dot would also accept the x in "ABx12". Requiring exactly two digits would reject the valid one-digit example.

Question 10 of 10

An input "R8: 24 kg" must become numeric 24 without losing the code or accepting other units. What pipeline fits that task?
  1. Parse the whole input, then keep its first numeric result as the measurement.
  2. Remove all nondigits, then convert the remaining digits into a measurement.
  3. Validate the kg suffix, split the code from the measurement, then parse the measurement.
  4. Extract the first digit run, then check whether the input contains a kg suffix.
Show answerHide answer
Answer: C
The code itself contains a digit, so parsing the whole string would return 8, not the measurement. Splitting preserves the code and isolates "24 kg"; checking the unit protects its meaning before parsing. Removing every nondigit would merge unrelated digits into 824.
Set 2: Conditions and numeric decisions10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A table has scores c(72, 88, 88, 94, 61). After keeping min_rank(desc(score)) <= 2, what are the retained count and mean score?
  1. 2 rows; mean 91
  2. 3 rows; mean 86
  3. 3 rows; mean 90
  4. 2 rows; mean 88
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

In day order, a station has readings c(14, 11, 18, 16). What is value - lag(value)?
  1. NA 3 -7 2
  2. -3 7 -2 NA
  3. 14 -3 7 -2
  4. NA -3 7 -2
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

What does c(7, NA, 12) >= 10 return?
  1. FALSE FALSE TRUE
  2. TRUE NA FALSE
  3. FALSE NA TRUE
  4. FALSE TRUE TRUE
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

For x <- c(2, NA, 8, 11), what does (x > 6) | is.na(x) return?
  1. FALSE TRUE TRUE TRUE
  2. FALSE NA TRUE TRUE
  3. TRUE FALSE TRUE TRUE
  4. FALSE TRUE FALSE TRUE
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A sensor records x <- c(4, NA, 9, 13, 6). What is mean(x > 7, na.rm = TRUE)?
  1. 0.4
  2. 0.6
  3. 0.75
  4. 0.5
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

What labels result for x <- c(17, 25, NA)?

case_when(x >= 20 ~ "large", x >= 15 ~ "medium", .default = "small")
  1. "medium" "large" NA
  2. "medium" "large" "small"
  3. "small" "medium" NA
  4. "large" "large" "small"
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

How many whole hours and leftover minutes are in 197 minutes, using %/% and %%?
  1. 3 hours and 37 minutes
  2. 3 hours and 17 minutes
  3. 2 hours and 77 minutes
  4. 4 hours and 17 minutes
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

What values result from pmax(pmin(c(-3, 7, 19), 12), 0)?
  1. 0 0 0
  2. -3 7 12
  3. 0 7 19
  4. 0 7 12
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

What labels does this code produce?

cut(c(0, 10, 20), breaks = c(0, 10, 20), labels = c("low", "high"))
  1. NA "low" "high"
  2. "low" "high" "high"
  3. "low" "low" "high"
  4. NA "high" NA
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

An audit has outcomes c(TRUE, FALSE, NA, TRUE). It reports all(outcome, na.rm = TRUE) and mean(outcome, na.rm = TRUE). What should those results say?
  1. Not all known cases pass; two thirds of known cases pass.
  2. All known cases pass; half of all recorded cases pass.
  3. Not all known cases pass; half of known cases pass.
  4. The test is unknown; two thirds of all recorded cases pass.
Show answerHide answer

Save this lesson to see this answer.

Set 3: Categories and calendar data10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What does as.numeric(factor(c("30", "10", "20"))) return?
  1. 3 1 2
  2. 30 10 20
  3. 1 2 3
  4. 10 20 30
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

An allowed rating set is c("low", "medium", "high"), but one entry is "hig". How do factor() and forcats::fct() behave when both receive those explicit levels?
  1. Both stop with errors before producing a factor.
  2. Both add "hig" as a fourth allowed level.
  3. factor() makes NA; fct() stops with an error.
  4. factor() stops; fct() silently makes NA.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

Category A has measurements 1, 2, 18, and category B has 5, 6, 7. In what order does default fct_reorder(category, value) put the levels?
  1. B, then A, using means 6 and 7.
  2. A, then B, using counts 3 and 3.
  3. B, then A, using maxima 7 and 18.
  4. A, then B, using medians 2 and 6.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

Counts are oak 4, pine 4, birch 2, and elm 1. What counts follow fct_lump_n(tree, n = 1) with default tie handling?
  1. oak 4, Other 7
  2. oak 4, pine 4, Other 3
  3. pine 4, Other 7
  4. oak 4, pine 4, birch 2, elm 1
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

How do you rename the existing factor label "scooter" to "Small vehicle"?
  1. fct_recode(mode, "Small vehicle" = "scooter")
  2. fct_recode(mode, "scooter" = "Small vehicle")
  3. fct_relevel(mode, "Small vehicle", after = Inf)
  4. fct_drop(mode, only = "scooter")
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A source uses day-month-year dates. What does dmy("08/09/2027") represent?
  1. August 9, 2027
  2. September 9, 2027
  3. August 8, 2027
  4. September 8, 2027
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

What date does make_date(2027, 6, 14) create?
  1. 2027-14-06
  2. 2027-06-14
  3. 2027-01-14
  4. 2027-06-01
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Events occur in March 2025 and March 2026. What grouping key keeps their monthly totals separate and remains suitable for a date axis?
  1. month(t)
  2. month(t, label = TRUE)
  3. floor_date(t, "month")
  4. mday(t)
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A Tokyo event is 2027-01-02 00:30:00 in "Asia/Tokyo". Tokyo is nine hours ahead of UTC. What does with_tz(x, "UTC") display, and does the event move?
  1. January 2 at 09:30 UTC; the instant stays fixed.
  2. January 1 at 15:30 UTC; the instant stays fixed.
  3. January 2 at 00:30 UTC; the instant changes.
  4. January 1 at 15:30 UTC; the instant changes.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A renewal starts on 2027-01-31. It is scheduled with %m+% months(1), then another %m+% months(1) is applied to that result. What is the second renewal date?
  1. 2027-03-28
  2. 2027-03-31
  3. 2027-03-03
  4. NA
Show answerHide answer

Save this lesson to see this answer.

Set 4: Missing values and trustworthy summaries10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A table has four rows: scores 8, 9, NA, 12 and comments "ok", NA, "check", "ok". How many rows remain after drop_na(df, score)?
  1. 2 rows
  2. 1 row
  3. 3 rows
  4. 4 rows
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does sum(is.na(c(6, NA, NaN, 2))) return?
  1. 1
  2. 3
  3. NA
  4. 2
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A documented missing code is -88. For x <- c(5, -88, 11, NA), what is mean(na_if(x, -88), na.rm = TRUE)?
  1. -24
  2. 8
  3. 4
  4. 5.5
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What is coalesce(c(NA, 7, NA), c(4, NA, NA), 2)?
  1. 4 7 2
  2. 2 7 2
  3. 4 NA 2
  4. 4 7 NA
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

Site P has days 1, 2, and 3; site Q has days 1 and 3. A present P-day-2 reading is NA. After complete(df, site, day = 1:3), how many rows and how many gap types are represented?
  1. 5 rows, with only the explicit gap represented.
  2. 6 rows, with only the originally implicit gap represented.
  3. 6 rows, with both explicit and originally implicit gaps.
  4. 7 rows, with both explicit and originally implicit gaps.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A complete log omits zero-event days. Counts 2, 5, and 1 are recorded on days 1, 3, and 5. What is the mean count per day over days 1 through 5?
  1. 2.67
  2. 1.6
  3. 2
  4. 1
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A retained factor group has no rows. What does its n() report?
  1. 0
  2. NA
  3. NaN
  4. Inf
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

For waiting times c(2, 3, 4, 5, 41), what are the median and mean?
  1. Median 11; mean 4
  2. Median 4; mean 10
  3. Median 5; mean 11
  4. Median 4; mean 11
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

A complete device-event log omits days with zero events. It contains day 1 count 4, day 2 count NA from a damaged record, and day 4 count 2. How should days 1:4 be completed without turning the damaged record into a known zero?
  1. complete(df, day = 1:4, fill = list(n = 0))
  2. complete(df, day = 1:4) |> mutate(n = coalesce(n, 0))
  3. complete(df, day = 1:4, fill = list(n = 0), explicit = FALSE)
  4. complete(df, day = 1:4) |> drop_na(n)
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

For x <- c(2, NA, 10, 15), an analyst separately filters x > 8 and !(x > 8). How many rows appear across both outputs, and why?
  1. 4 rows; negation makes the missing condition true.
  2. 3 rows; the unknown condition is dropped from both.
  3. 3 rows; the missing value is counted as a false result.
  4. 4 rows; each recorded row must belong to one output.
Show answerHide answer

Save this lesson to see this answer.

Set 5: Combine cleaning steps10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

What does str_length("") return?
  1. NA
  2. 0
  3. 1
  4. NaN
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

What does parse_number("2.450,8 kg", locale = locale(decimal_mark = ",", grouping_mark = ".")) return?
  1. 2.4508
  2. 24508
  3. 2450.8
  4. 2.45
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A rating factor has levels "Low", "Medium", "High". Why would ordering it by response frequency be a poor display choice?
  1. It would hide the rating scale’s meaningful sequence.
  2. It would replace each rating with its frequency count.
  3. It would silently remove all unused rating levels.
  4. It would make every rating become an unordered string.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

What does hour(t) + minute(t) / 60 give for a time of 09:45:00?
  1. 9.45
  2. 9.25
  3. 10.25
  4. 9.75
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

The strings are c("Code 62 then 9", "No code", "Code 18 then 7"). After str_extract(x, "[0-9]+"), numeric parsing, and mean(..., na.rm = TRUE), what is the mean?
  1. 24
  2. 26.67
  3. 48
  4. 40
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

A factor has counts A 6, B 3, C 3. After fct_lump_prop(f, prop = 0.25), what counts remain?
  1. A 6, B 3, C 3
  2. A 6, Other 6
  3. Other 12 only
  4. A 6, B 3, Other 3
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A city advances its clocks by one hour overnight. At noon before the change, t + ddays(1) and t + days(1) are scheduled. What local times result the next day?
  1. Duration: 13:00; period: 12:00.
  2. Duration: 12:00; period: 13:00.
  3. Duration: 12:00; period: 12:00.
  4. Duration: 13:00; period: 13:00.
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

Rows arrive as (site, day, value): (A, 2, 13), (B, 1, 40), (A, 1, 8), (B, 2, 35). What are day-2 changes for A and B when calculated correctly?
  1. A: -27; B: +27.
  2. A: -5; B: +5.
  3. A: +5; B: -5.
  4. A: +13; B: +35.
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

Three recorded rows have primary readings c(NA, 8, NA) and backup readings c(6, NA, NA). What can a coalesced mean and a missing count honestly report?
  1. Mean 4.67 among three known rows; no row remains unknown.
  2. Mean 7 among two known rows; one row remains unknown.
  3. Mean 8 among one known row; two rows remain unknown.
  4. Mean 6 among two known rows; one row remains unknown.
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A factor has allowed levels North, South, West, but rows only for North and South. What preserves the full category count table and describes West’s numeric mean correctly?
  1. Drop levels, count normally, and report West’s mean as zero.
  2. Keep levels, count normally, and report West’s mean as zero.
  3. Fill every measurement with zero, then report West as observed.
  4. Keep levels, count with .drop = FALSE, and report West as having no data.
Show answerHide answer

Save this lesson to see this answer.

Set 6: Diagnose plausible results10 Practice Questions

Save this lesson to see every answer and practice every set.

Question 1 of 10

A date is 2027-01-31. After update(x, month = 2), what do month() and mday() report for the result?
  1. Month 2 and day 28.
  2. Month 3 and day 3.
  3. Month 2 and day 31.
  4. Month NA and day NA.
Show answerHide answer

Save this lesson to see this answer.

Question 2 of 10

A timestamp reads 2027-06-10 10:00:00 UTC, but the source confirms it was a Tokyo clock reading assigned UTC by mistake. Tokyo is nine hours ahead of UTC. What repair and UTC instant fit the source?
  1. with_tz(x, "Asia/Tokyo"); 10:00 UTC on June 10.
  2. force_tz(x, "Asia/Tokyo"); 19:00 UTC on June 10.
  3. with_tz(x, "Asia/Tokyo"); 01:00 UTC on June 10.
  4. force_tz(x, "Asia/Tokyo"); 01:00 UTC on June 10.
Show answerHide answer

Save this lesson to see this answer.

Question 3 of 10

A lab expects sites A and B on days 1, 2, and 3. Rows are A-day-1 value 2, A-day-3 value 4, B-day-1 value 8, and B-day-3 value NA. Offline readings are unknown. After completion, what are the total row count, missing count, and known-reading mean?
  1. 4 rows; 1 missing; mean about 4.67.
  2. 6 rows; 1 missing; mean about 2.33.
  3. 6 rows; 3 missing; mean about 4.67.
  4. 6 rows; 3 missing; mean about 2.33.
Show answerHide answer

Save this lesson to see this answer.

Question 4 of 10

A column records only a calendar day, with no useful clock information. What R class is the simplest fit?
  1. POSIXct
  2. hms
  3. character
  4. Date
Show answerHide answer

Save this lesson to see this answer.

Question 5 of 10

A table has names Imani and Pavel in team Z. What row-level effect follows mutate(label = str_flatten(name, ", "), .by = team)?
  1. Both rows receive "Imani, Pavel".
  2. One row remains with "Imani, Pavel".
  3. Each row keeps only its own name.
  4. Two new rows are added for the names.
Show answerHide answer

Save this lesson to see this answer.

Question 6 of 10

For x <- c(5, NA, 9), what rows survive filter(df, x %in% c(5, NA))?
  1. Only the row with 5.
  2. The rows with 5 and NA.
  3. The rows with 5 and 9.
  4. All three recorded rows.
Show answerHide answer

Save this lesson to see this answer.

Question 7 of 10

A factor contains "6", "12", "6", "3" with default levels. An analyst averages as.numeric(f) and gets 2.25. What mean of the recorded quantities should replace it?
  1. 2.25
  2. 7
  3. 6.75
  4. 5.25
Show answerHide answer

Save this lesson to see this answer.

Question 8 of 10

A pattern intended to allow only "sun" or "moon" is written "^sun|moon$". What replacement rejects both "sunny" and "honeymoon" while accepting the two complete words?
  1. "^(sun|moon)$"
  2. "^sun|moon$"
  3. "^(sun|moon)"
  4. "(sun|moon)$"
Show answerHide answer

Save this lesson to see this answer.

Question 9 of 10

After all "late" rows are filtered out, a factor still allows levels early, on-time, late. The report must show late with zero observations. What should happen next?
  1. Use fct_drop() and then count(df, status).
  2. Keep the levels and use count(df, status) with its default settings.
  3. Keep the levels and use count(df, status, .drop = FALSE).
  4. Drop unused levels and then use count(df, status, .drop = FALSE).
Show answerHide answer

Save this lesson to see this answer.

Question 10 of 10

A form records a person’s name only on their first row, followed by blank name cells for their later rows. Measurements may also be missing. What cleaning choice respects these two recording meanings?
  1. Fill the repeated name labels in order and keep unknown measurements as NA.
  2. Fill both names and measurements downward because both contain blanks.
  3. Fill the names and replace missing measurements with zero before summarizing.
  4. Drop every row missing either a name or a measurement before grouping.
Show answerHide answer

Save this lesson to see this answer.

Stuck on your own question? Homework Help

Key Terms

82 Key Terms, each with its definition

A

Anchor
An anchor is a regex marker that matches a position, such as the start or end of a string, without consuming a character.
Pair ^ and $ around a code pattern when the entire value must follow the required layout.

B

Backreference
A backreference refers to a previously captured regex group, letting replacement text reuse that group's matched characters.
In an ordinary R replacement string, "\\2" refers to the text captured by the second group.
Boolean condition
A Boolean condition asks whether a rule holds and can be combined with other conditions using logical operators such as and, or, and not.
A reading passes value >= 0 & value <= 100 only when it meets both limits for the allowed range.

C

Capture group
A capture group is a parenthesized regex part whose matched text can be retained and referred to in a later replacement.
Capture year, month, and day separately to rearrange their order while retaining the same pieces.
Character class
A character class specifies a set of allowed characters and matches one character from that set at a given position.
The class [A-F] accepts one capital letter from A through F, not a whole string of such letters.
Coalescing
Coalescing chooses the first available non-missing value among corresponding inputs, supplying a justified alternative for each position.
Combine a primary reading and a backup reading with coalesce() while retaining missingness if both are unknown.
Collapsing levels
Collapsing levels combines selected existing categories into a shared new category with a label describing the merged group.
fct_collapse() can combine train and bus responses into one category called "Public transport".
Complete-case removal
Complete-case removal discards rows with missing values in all selected analysis columns, changing the set of observations retained.
Name score in drop_na() when a missing comment should not cause a valid score to be discarded.
Completion
Completion adds rows for absent combinations of supplied values, turning implicit missingness into visible explicit cells.
complete(site, day = 1:7) can reveal a day missing from every site's recorded observations.
Component update
A component update changes selected parts of a date-time while retaining others, with invalid combinations able to roll onward.
Updating January 31 to February in a non-leap year can produce a March date instead of February.
Conditional recoding
Conditional recoding creates an output value for each observation according to one or more logical tests of its recorded values.
if_else() can label known readings as "inside" or "outside" and label unknown conditions separately.
Cumulative total
A cumulative total is a running sum that includes all values from the beginning of a sequence through the current position.
Arrange daily rows by date before using cumsum() to describe how the total grew over time.

D

Date
A date identifies a calendar day without a clock time, represented by R's Date class and displayed as <date> in a tibble.
A service log can store a delivery day as a date when the hour and minute do not affect the analysis.
Date component
A date component is one part of a date or date-time, such as its year, month, day of month, weekday, or clock hour.
Extracting month(t) groups by month number, so include the year when observations span several years.
Date rounding
Date rounding moves a date or date-time to a unit boundary, supporting calendar groups such as months or weeks.
floor_date(t, "month") assigns events to their month start while retaining their calendar year.
Date-time
A date-time identifies an instant using a date and clock time interpreted in a time zone, commonly stored as POSIXct in R.
A meeting timestamp needs a zone so people in different places can refer to the same event.
Delimiter
A delimiter is a separator marking boundaries between text fields or items, such as the hyphen in a structured code.
A wider split turns the hyphen-separated parts of "CA-2027-008" into separate text columns.
Double
A double is R's usual floating-point numeric storage type, used for decimal values and for ordinary number literals without an L.
The literal 7 is stored as a double even though its written value has no fractional part.
Duration
A duration is a fixed number of elapsed seconds, independent of how calendar units or local clocks label the interval.
dhours(24) stays 24 elapsed hours even when a daylight saving change moves the local clock.

E

Elementwise limit
An elementwise limit caps or floors each value separately, preserving one output for every input instead of returning one summary.
pmax(c(-3, 2, 7), 0) makes each negative entry zero while keeping the positive entries unchanged.
Empty group
An empty group is a defined category or combination with no observed rows, so its count is zero and its measurements have no data.
Retaining unused factor levels can show an empty group's count without inventing a measured mean.
Encoding
An encoding specifies how stored bytes represent text characters, which must be interpreted correctly when a file is imported.
Garbled accented names can require the file's actual encoding in readr's locale() argument.
Escape sequence
An escape sequence uses a backslash to represent a special character inside an ordinary quoted R string.
The code "line 1\nline 2" stores a line break, which writeLines() displays on separate lines.
Explicit missing value
An explicit missing value is an unknown value recorded as an NA cell in a row that is present in the dataset.
A response row containing NA for score is present in the data even though its score is unknown.

F

Factor
A factor stores categorical observations as integer codes pointing to a defined set of text labels called levels.
A month factor with calendar levels sorts "Feb" before "Dec" even though text sorting would differ.
Factor reordering
Factor reordering changes the sequence of levels used by tables, axes, or legends without changing each observation's category.
A boxplot can order nominal categories by median measurement to make the comparison easier to read.
First-match rule
A first-match rule assigns each observation the result of the earliest true condition, so later matching conditions do not replace it.
In case_when(), put a high threshold before a broader lower threshold when defining ordered bands.
Floating-point tolerance
A floating-point tolerance is a small permitted numeric difference used to compare calculated decimals affected by binary storage.
near() can recognize equivalent decimal calculations that a direct == comparison treats as different.
Frequency order
A frequency order arranges categories by their number of observed rows, usually from most common to least common.
fct_infreq() may put a common low-valued category before a rare category with a much higher median.

G

Greedy matching
Greedy matching makes a quantifier take as much text as it can while the overall regular expression still matches.
A greedy tag pattern can span two marked sections; a lazy quantifier can stop at the first closing tag.

I

Implicit missing value
An implicit missing value is an expected observation absent as a whole row, leaving no NA cell for ordinary checks to find.
A missing site-day row needs an expected site-day set before the gap can be identified and added.
Integer
An integer is a whole-number storage type in R, written explicitly with an L suffix or produced by sequences such as 1:3.
typeof(7L) identifies integer storage, while dividing that value can produce a double result.
Internal code
An internal code is the integer stored for a factor observation that identifies its label's position in the level list.
Direct numeric conversion returns the code, so convert through text before reading numeric labels.
Interquartile range
The interquartile range is the distance between the 75th and 25th percentiles, describing the spread of the middle half of values.
Use IQR(x) with a median when you want a spread measure that is less sensitive to extreme values.
Interval
An interval is a time span with definite start and end instants, allowing its actual calendar and elapsed lengths to be measured.
Calculate whole years between a birth date and a reference date using an anchored interval.
ISO 8601 date
An ISO 8601 date writes components from largest to smallest in year-month-day order, making numeric date text unambiguous.
The date "2027-08-19" identifies August 19 directly without a day-first versus month-first choice.

K

Known zero
A known zero records a confirmed absence of events or quantity, keeping that observation distinct from an unknown measurement.
In a complete event log that omits zero-event days, an absent day can legitimately be completed with zero.

L

Lag
A lag is an earlier value aligned with a later position, allowing each row to be compared with a preceding observation.
After sorting dates within each site, subtract lag(value) to calculate change from its previous reading.
Level
A level is an allowed factor label with a place in the factor's ordering, whether or not observations currently use it.
A survey can retain "No response" as a possible level even when no current row has that label.
Literal matching
Literal matching searches for the specified characters themselves, ignoring the special meanings those characters have in regex.
fixed("a.b") accepts the literal dot, so it does not treat "axb" as a match for that pattern.
Locale
A locale supplies language and regional rules for operations such as sorting, case conversion, numeric parsing, and date labels.
Setting a Turkish locale changes how the lowercase letter i is converted into its uppercase form.
Logical count
A logical count is the sum of true conditions, using R's arithmetic conversion of true to 1 and false to 0.
sum(mass > 12, na.rm = TRUE) counts known measurements above 12 kg without recovering unknown ones.
Logical proportion
A logical proportion is the mean of a logical condition, expressing the share of evaluated cases that are true.
Removing unknown answers from a condition's mean also removes those cases from its denominator.
Logical vector
A logical vector stores true, false, or unknown answers, often produced by comparing each observation with a value or rule.
c(4, NA, 9) > 6 gives a false answer, an unknown answer, and a true answer in the original order.
Lumping
Lumping combines levels selected by a frequency rule into an other category, making a table or plot easier to read.
Keeping the two most common categories may retain more than two when levels tie at the cutoff.

M

Median
The median is the middle position of ordered data, giving a measure of center that resists the pull of extreme observations.
A long-tailed waiting-time distribution can have a mean far above its median because of a few long waits.
Membership test
A membership test checks whether each value appears anywhere in a supplied set, which R expresses with the %in% operator.
region %in% c("East", "West") retains either named region regardless of its row position.
Metacharacter
A metacharacter is a regex symbol with a special pattern meaning, requiring escaping when its literal character is intended.
A dot normally matches a character; fixed(".") searches for the punctuation itself instead.
Missing-value level
A missing-value level is an explicit factor category created to display previously missing values as a named group.
Naming missing responses "(missing)" makes them visible in a plot without recovering their answers.
Month rollback
Month rollback adjusts an impossible month-arithmetic result to the last valid day in the intended target month.
January 31 plus one month with %m+% reaches February 28 in 2026 and February 29 in 2028.

N

NaN
NaN means "not a number" and marks a numeric calculation without a numeric result, such as zero divided by zero.
An empty group's mean is NaN; check its count before treating the output as an observed measurement.
Nominal category
A nominal category is a group label without an intrinsic ranking, so its display order can be chosen to aid comparison.
Travel modes can be ordered by frequency without implying that cycling ranks above taking a bus.
Numeric bin
A numeric bin is an interval used to group values into categories, with defined boundaries and a rule for including its endpoints.
cut() places a value equal to an internal break in the lower bin when its default upper-inclusive rule applies.
Numeric parsing
Numeric parsing converts text representing a number into numeric data according to rules for decimal marks and other formatting.
parse_number("Mass: 8 kg") returns a number, but the removed unit still matters for interpretation.

O

Ordered factor
An ordered factor declares that its levels form a ranked scale, enabling comparisons based on that level ordering.
Create low, medium, and high as ordered levels when their ranking is part of the variable's meaning.
Ordinal category
An ordinal category belongs to a meaningful ranked scale whose sequence should remain visible when results are displayed.
Keep "Disagree", "Neutral", and "Agree" in scale order even when "Neutral" is the most common response.

P

Pattern detection
Pattern detection returns a logical answer for each string, indicating whether its text contains a match for a supplied pattern.
Feed str_detect() into filter() to keep names starting with a required prefix in a text column.
Pattern extraction
Pattern extraction returns matched text from a string, with first-match and all-match functions providing different output shapes.
Extracting digits from "Batch 18, sample 72" gives only "18" with str_extract(), still as text.
Period
A period is a span in calendar or clock units whose elapsed length depends on the date-time to which it is applied.
days(1) can preserve tomorrow's local hour while spanning fewer or more than 24 elapsed hours.
Placeholder code
A placeholder code is a recorded label or number used to stand for missing data instead of the ordinary missing value NA.
Convert -88 with na_if() only when the data documentation identifies it as missing in that column.

Q

Quantifier
A quantifier specifies how many times the preceding regex character, class, or group may repeat in a match.
In [0-9]{3}, the class selects digits and the quantifier requires a run of exactly three.
Quantile
A quantile is a value marking a specified proportional position in a distribution, such as the quarter or three-quarter position.
Comparing the 25th and 75th percentiles shows how widely the central half of the readings is spread.

R

Rank
A rank describes a value's ordered position among observations, with a chosen rule for assigning positions to equal values.
Two tied third-place scores can both pass a top-three rank filter, making four retained rows.
Raw string
A raw string is an R text literal that keeps backslashes as written, avoiding ordinary quoted-string escape processing.
A raw path such as r"(C:\logs)" needs no doubled backslash for R's string-reading layer.
Recoding
Recoding changes category labels or assigns existing labels to new groups, according to a stated mapping of old values to new ones.
In fct_recode(), put the replacement label on the left and the existing label on the right.
Recycling
Recycling repeats a shorter vector during an operation so its elements can be paired with every element of a longer vector.
Adding one constant to a column is useful recycling; alternating two targets can misalign a comparison.
Regular expression
A regular expression is a text pattern built from literal characters and special symbols that describe what can match.
A code check can require a fixed number of capital letters followed by a fixed number of digits.
Run
A run is an uninterrupted sequence of identical values, ending when the recorded value changes to something different.
consecutive_id() assigns a new run number when a status returns after a different status has appeared.

S

String
A string is a text value containing a sequence of characters, written between quotes in R even when it consists only of digits.
Keep an identifier such as "0048" as a string so its leading zeros remain part of the recorded value.
String flattening
String flattening combines all elements of a text vector into one string, using chosen separators between the original values.
In summarize(), flattening the member column produces one readable member list for each team.
String interpolation
String interpolation inserts values or calculation results into a text template, such as expressions inside braces in str_glue().
A template can insert each row's name and count to create a separate message for that observation.
Substring
A substring is a consecutive portion of a string, selected by its position or by a pattern describing the desired text.
str_sub(code, -3, -1) extracts the final three characters without depending on the code's full length.

T

Time of day
A time of day is a clock reading without a calendar date, commonly stored in R using the hms class.
The value "16:45:00" can describe a daily closing time without identifying a particular day's instant.
Time zone
A time zone supplies the rules for displaying instants as local clock readings, including any daylight saving changes.
An IANA name such as "Asia/Tokyo" identifies the intended zone more clearly than an ambiguous abbreviation.
Time-zone conversion
A time-zone conversion changes how an instant is displayed in another zone while preserving its position on the timeline.
with_tz() may show the previous date in another zone even though the recorded event has not moved.

U

Unicode equivalence
Unicode equivalence recognizes character sequences with the same textual meaning even when their stored character forms differ.
str_equal() can match a composed accented letter to the same letter followed by a combining accent.
Unix epoch
The Unix epoch is the origin 1970-01-01 used for numeric time values, counted in days for dates and seconds for date-times.
Numeric as_date(2) advances two days, while as_datetime(2) advances only two seconds.
Unused level
An unused level is an allowed factor category that currently has no observations, often remaining after rows have been filtered.
Use .drop = FALSE to show its zero count, or fct_drop() when the category should be removed.

V

Vectorized operator
A vectorized operator applies an operation to corresponding elements, returning answers across a vector instead of one overall answer.
Use & to combine two column conditions so each row receives its own combined logical result.

W

Week start
A week start specifies the first weekday in numbering and weekly rounding, which changes the assignment of dates to weeks.
Use week_start = 1 consistently when reports define weeks as beginning on Monday.
Whitespace
Whitespace consists of spacing characters, including spaces, tabs, and line breaks, which can make otherwise similar labels differ.
str_squish() turns repeated internal spaces into one space and removes unwanted outer spacing.
Word boundary
A word boundary is a position between word and nonword text, or a string edge beside word text, marked by \b in regex.
Word boundaries let an "apple" search match "apple pie" while rejecting the ending inside "pineapple".

About this lesson

By StudeliReport a mistake

Make your own Study Materials

Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.

Get Started