- Learn
- Computer Science & IT
- Data Science & AI
- Data Analysis with R
- Strings and Factors in R
Strings and Factors in R
Strings, Factors, Dates and Missing Values in R
IntermediateLesson 5 of 7 in Data Analysis with R Course
What you will learn
- Build and combine conditions, use logical vectors to count and recode values, and transform, rank and summarize numeric columns.
- Compare values and combine conditionsWrite 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 vectorsSummarize conditions with
sum(),mean(),any()andall(), subset with logical vectors, and create new values withif_else()andcase_when(). - Parse and transform numbersTurn text into numbers, use vectorized arithmetic and recycling safely, and round, bin and accumulate numeric columns.
- Rank, shift and summarize numbersRank values, compare each value with the one before it, and choose summaries of center, spread and position that suit the data.
- Compare values and combine conditions
- Create and combine strings, tidy and split messy text columns, and use regular expressions to detect, count, replace and extract patterns.
- Create and combine stringsWrite strings with quotes, escapes and raw strings, see their real contents, and combine them with
str_c(),str_glue()andstr_flatten(). - Inspect, tidy and split stringsMeasure 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 patternsBuild patterns from literal characters, metacharacters, quantifiers, character classes, anchors and groups, and write them correctly as R strings.
- Detect, count, replace and extract patternsUse regular expressions with stringr and tidyr to filter rows, count matches, clean values, pull out parts of strings and split columns.
- Create and combine strings
- 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 levelsExplain 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 plotsOrder levels by a summary, by frequency or by hand, so that tables, bar charts and legends read clearly.
- Rename, combine and lump factor levelsChange level labels with
fct_recode(), merge levels withfct_collapse(), group rare levels into an "Other" level, and handle missing and unused levels.
- Create factors with the right levels
- 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 dataChoose between dates, times and date-times, and create them from text, numbers or separate columns, resolving ambiguous formats.
- Extract, round and update date componentsPull out years, months, weekdays and hours, round date-times to a unit for grouping, and change individual components.
- Calculate with time spans and time zonesMeasure time with durations, periods and intervals, add days and months correctly, and convert between time zones.
- Create dates and date-times from data
- 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 valuesCount missing values, tell
NAfromNaN, turn placeholder codes intoNA, fill or replace values with care, and decide when to drop rows. - Reveal implicit missing values and empty groupsRecognize rows that are absent from the data, make them visible with
pivot_wider()andcomplete(), and report empty factor groups correctly.
- Find and handle explicit missing values
Strings and Factors in R study guide
1Work 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
| Operator | Meaning | Example |
|---|---|---|
& | Both conditions hold | temps > 20 & temps < 30 |
| | At least one holds | temps < 20 | temps > 30 |
! | Reverse a logical answer | !(temps > 24) |
xor() | Exactly one holds | xor(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 andnear()for calculated decimal equality. - Combine column conditions with
&,|,!, andxor(). - Use
is.na()to test missingness; comparisons withNAstay unknown. - Use
%in%to test membership in a set, includingNAwhen 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 = TRUEchanges 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.
| Need | Function | Example result |
|---|---|---|
| One minimum overall | min(c(3, 8, 5), 6) | 3 |
| A cap for every element | pmin(c(3, 8, 5), 6) | 3 6 5 |
| A lower limit of zero | pmax(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()andpmax()return elementwise limits, whilemin()andmax()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.
| Summary | What 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(), androw_number(). - Arrange and group before using
lag()orlead()to measure changes. - Median and IQR resist outliers; mean and standard deviation are sensitive to them.
- Report missing counts alongside summaries of known values.
2Clean 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()orstr_view()reveals a string’s contents.str_c()andstr_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 part | Meaning |
|---|---|
? | 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.
3Recode 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 intoNA;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.
| Function | Rule 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 = FALSEto report them.
4Work 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()andmake_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_startto 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
| Type | Meaning | Example |
|---|---|---|
| Duration | Exact seconds | dhours(36) |
| Period | Calendar or clock units | months(1) |
| Interval | Fixed start and end | start %--% 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.
5Treat 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. NaNsignals a numeric calculation without a numeric result; it is also detected byis.na().- Convert documented placeholder codes with import settings or
na_if(). - Use
fill()for repeated labels andcoalesce()for justified alternatives. - Dropping rows or replacing unknown values can change or bias a result.
na.rm = TRUEdescribes 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
NAcell; implicit missingness is an absent expected row. pivot_wider()andcomplete()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 = FALSElimitscomplete()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
1Turn readings into conditions, labels, and changes
18 steps
- 1IntroductionChoose 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
dplyrfor the examples. - 2ExampleRead a condition position by position
temp <- c(16, 27, NA, 23) temp > 22 # FALSE TRUE NA TRUEThe 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 == NAcannot find it: comparing any value with an unknown value produces an unknown answer. - 3ExplanationBuild 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 expressiontemp == 16 | 23is 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. - 4ChallengeCan an unknown side change the answer?
What are
TRUE | NAandTRUE & NA, and why do they differ?---reveal---
The first is
TRUE: an or condition is already satisfied by its known true side. The second isNA: 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. - 5TipCheck decimal equality with a tolerance
Calculated decimals are stored in binary, so exact equality can fail after arithmetic.
0.1 + 0.2 == 0.3is false, whilenear(0.1 + 0.2, 0.3)is true.Use
==for an exact equality test andnear()when comparing calculated decimals. Equality needs two equals signs: in a dplyr call, a single=names an input instead of expressing the intended comparison. - 6ExampleCount known warm readings
sum(temp > 22, na.rm = TRUE) # 2 mean(temp > 22, na.rm = TRUE) # 0.6666667True 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.
- 7ExplanationChoose 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. - 8ExampleRead 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.
- 9ChallengeKeep 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 anNAplaceholder for the unknown comparison. - 10ExampleParse the number and retain its meaning
readr::parse_number(c("18 kg", "62%")) # 18 62Parsing 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.
- 11ExplanationLimit each reading separately
pmin(c(3, 14, 9), 10) # 3 10 9 min(c(3, 14, 9), 10) # 3pmin()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.
- 12ExampleSeparate whole units from a remainder
A process takes 158 minutes.
158 %/% 60gives two whole hours, and158 %% 60gives 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.
- 13ChallengeCheck a bin boundary
With
cut(x, breaks = c(0, 10, 30)), where does 10 go? What changes withright = FALSE?---reveal---
The default assigns 10 to
(0,10], the lower interval, because its upper endpoint is included. Withright = FALSE, 10 belongs to[10,30). The default intervals exclude zero; the first lower-inclusive interval includes it. Check endpoints before giving bins names. - 14TipArrange before accumulating
A running total follows the vector's current order:
cumsum(c(4, 6, 3))is4 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, sofloor(-1.8)is -2. To round to a fixed increment, divide by that increment, round, and multiply back. - 15ExampleChoose 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 4The first two methods give equal values equal ranks; only
min_rank()leaves a gap.row_number()breaks ties by order. Usedesc(x)for largest-first ranking. A rank cutoff includes every tie at its boundary, so the number of selected rows can exceed the cutoff. - 16ExampleMeasure 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.
- 17ChallengeCombine 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.
- 18RecapMake 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.
2Clean text and build a code checker
20 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionRead text before changing it
- 2ExplanationSeparate stored text from its printed form
- 3ExampleCreate one label per row
- 4ChallengeChoose row labels or a group list
- 5TipDo not confuse missing text with the letters NA
- 6ExampleClean a label and preserve its code
- 7ExplanationInspect length and character positions
- 8ExampleSplit fields into columns
- 9ChallengeSplit several items without creating several fields
- 10Key InsightLookalike text can still differ
- 11ExampleStart with the characters a code allows
- 12ExampleRequire the whole value to match
- 13ExplanationEscape punctuation at both layers
- 14ChallengeGroup the choice before anchoring it
- 15ExplanationChoose how repetition should stop
- 16ExampleChoose a detection or a count
- 17ExampleExtract first, then convert the type
- 18ExampleReuse captured pieces in a replacement
- 19ChallengeKeep a unit check attached to its number
- 20RecapInspect the shape and meaning of the result
3Make category labels and displays reliable
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionKeep categories and observations separate
- 2ExampleDeclare the level set explicitly
- 3TipSurface unexpected labels early
- 4ChallengeRead numeric labels without averaging codes
- 5ExampleOrder nominal groups by their medians
- 6ExplanationChoose frequency or manual order
- 7ChallengeMatch the ordering to the question
- 8ConnectionRead a line legend at the right edge
- 9ExampleRename a level or merge a set
- 10ExampleLump with a rule you can explain
- 11ChallengePredict a tie at the lumping cutoff
- 12Key InsightA missing value is not an empty level
- 13ChallengeKeep the empty category in a report
- 14RecapCheck exactly what a factor operation changed
4Parse timestamps and choose the right kind of time
17 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart from what was recorded
- 2ExplanationChoose a type that matches the information
- 3ExampleMatch text order to a helper
- 4ChallengeResolve an ambiguous date from the source
- 5ExampleBuild from components and inspect failures
- 6ExampleExtract components for a useful question
- 7ExampleUse a date as the monthly group key
- 8ChallengeFind the calendar consequence of an update
- 9TipChoose a clock representation for plotting
- 10ExplanationPick seconds or calendar units
- 11ExampleFollow a clock change one step at a time
- 12ChallengeChoose a month-end rule
- 13ExampleAnchor a span to actual endpoints
- 14ExampleDisplay one event in another zone
- 15ChallengeRepair a clock assigned the wrong zone
- 16ChallengeParse first, then measure the requested span
- 17RecapCheck the meaning at both ends
5Find hidden gaps without inventing measurements
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionStart with the recording process
- 2ExampleCount unknown values before replacing them
- 3ExampleNormalize a documented placeholder
- 4ExplanationFill labels only when blanks mean repeat
- 5ChallengeKeep valid scores despite missing comments
- 6Key InsightKnown-value totals do not recover unknown contributions
- 7ExampleLook for a row that never existed
- 8ExampleComplete the expected combinations
- 9ChallengeDistinguish a zero day from a damaged count
- 10ExampleCount empty groups without inventing a mean
- 11ChallengeChoose the correct daily denominator
- 12RecapReport the gap and the decision together
Strings and Factors in R practice questions
Set 1: Strings and patterns10 Practice Questions
Question 1 of 10
str_c("Batch ", c("H2", "J7")) return?Show answerHide answer
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
name <- c("Mina", NA), how do str_c("Hi ", name) and str_glue("Hi {name}") differ at the second position?Show answerHide answer
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
str_sub(str_squish(" Lima Norte "), -5, -1) return?Show answerHide answer
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
str_pad("38", width = 5, pad = "0") return?Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
str_detect(c("7.2", "72", "7x2"), fixed(".")) return?Show answerHide answer
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
str_replace("2027/08/19", "/", "-") return?Show answerHide answer
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
str_count("abababa", "aba") return?Show answerHide answer
Question 9 of 10
"XAB.12" and "ABx12" while accepting "AB.7"?Show answerHide answer
Question 10 of 10
"R8: 24 kg" must become numeric 24 without losing the code or accepting other units. What pipeline fits that task?Show answerHide answer
Set 2: Conditions and numeric decisions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
c(72, 88, 88, 94, 61). After keeping min_rank(desc(score)) <= 2, what are the retained count and mean score?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
c(14, 11, 18, 16). What is value - lag(value)?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
c(7, NA, 12) >= 10 return?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
x <- c(2, NA, 8, 11), what does (x > 6) | is.na(x) return?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
x <- c(4, NA, 9, 13, 6). What is mean(x > 7, na.rm = TRUE)?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")
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
%/% and %%?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
pmax(pmin(c(-3, 7, 19), 12), 0)?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"))
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
c(TRUE, FALSE, NA, TRUE). It reports all(outcome, na.rm = TRUE) and mean(outcome, na.rm = TRUE). What should those results say?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
as.numeric(factor(c("30", "10", "20"))) return?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
c("low", "medium", "high"), but one entry is "hig". How do factor() and forcats::fct() behave when both receive those explicit levels?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
fct_reorder(category, value) put the levels?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
fct_lump_n(tree, n = 1) with default tie handling?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
dmy("08/09/2027") represent?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
make_date(2027, 6, 14) create?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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?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
drop_na(df, score)?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
sum(is.na(c(6, NA, NaN, 2))) return?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
x <- c(5, -88, 11, NA), what is mean(na_if(x, -88), na.rm = TRUE)?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
coalesce(c(NA, 7, NA), c(4, NA, NA), 2)?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
complete(df, site, day = 1:3), how many rows and how many gap types are represented?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
n() report?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
c(2, 3, 4, 5, 41), what are the median and mean?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
x <- c(2, NA, 10, 15), an analyst separately filters x > 8 and !(x > 8). How many rows appear across both outputs, and why?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
str_length("") return?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
parse_number("2.450,8 kg", locale = locale(decimal_mark = ",", grouping_mark = ".")) return?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
"Low", "Medium", "High". Why would ordering it by response frequency be a poor display choice?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
hour(t) + minute(t) / 60 give for a time of 09:45:00?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
fct_lump_prop(f, prop = 0.25), what counts remain?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
t + ddays(1) and t + days(1) are scheduled. What local times result the next day?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
(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?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
c(NA, 8, NA) and backup readings c(6, NA, NA). What can a coalesced mean and a missing count honestly report?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
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
2027-01-31. After update(x, month = 2), what do month() and mday() report for the result?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
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?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
mutate(label = str_flatten(name, ", "), .by = team)?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
x <- c(5, NA, 9), what rows survive filter(df, x %in% c(5, NA))?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
"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?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
"^sun|moon$". What replacement rejects both "sunny" and "honeymoon" while accepting the two complete words?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Anchor
^ and $ around a code pattern when the entire value must follow the required layout.B
Backreference
"\\2" refers to the text captured by the second group.Boolean condition
value >= 0 & value <= 100 only when it meets both limits for the allowed range.C
Capture group
Character class
[A-F] accepts one capital letter from A through F, not a whole string of such letters.Coalescing
coalesce() while retaining missingness if both are unknown.Collapsing levels
fct_collapse() can combine train and bus responses into one category called "Public transport".Complete-case removal
score in drop_na() when a missing comment should not cause a valid score to be discarded.Completion
complete(site, day = 1:7) can reveal a day missing from every site's recorded observations.Component update
Conditional recoding
if_else() can label known readings as "inside" or "outside" and label unknown conditions separately.Cumulative total
cumsum() to describe how the total grew over time.D
Date
<date> in a tibble.Date component
month(t) groups by month number, so include the year when observations span several years.Date rounding
floor_date(t, "month") assigns events to their month start while retaining their calendar year.Date-time
Delimiter
Double
7 is stored as a double even though its written value has no fractional part.Duration
dhours(24) stays 24 elapsed hours even when a daylight saving change moves the local clock.E
Elementwise limit
pmax(c(-3, 2, 7), 0) makes each negative entry zero while keeping the positive entries unchanged.Empty group
Encoding
locale() argument.Escape sequence
"line 1\nline 2" stores a line break, which writeLines() displays on separate lines.Explicit missing value
NA for score is present in the data even though its score is unknown.F
Factor
Factor reordering
First-match rule
case_when(), put a high threshold before a broader lower threshold when defining ordered bands.Floating-point tolerance
near() can recognize equivalent decimal calculations that a direct == comparison treats as different.Frequency order
fct_infreq() may put a common low-valued category before a rare category with a much higher median.G
Greedy matching
I
Implicit missing value
Integer
1:3.typeof(7L) identifies integer storage, while dividing that value can produce a double result.Internal code
Interquartile range
IQR(x) with a median when you want a spread measure that is less sensitive to extreme values.Interval
ISO 8601 date
K
Known zero
L
Lag
lag(value) to calculate change from its previous reading.Level
Literal matching
fixed("a.b") accepts the literal dot, so it does not treat "axb" as a match for that pattern.Locale
Logical count
sum(mass > 12, na.rm = TRUE) counts known measurements above 12 kg without recovering unknown ones.Logical proportion
Logical vector
c(4, NA, 9) > 6 gives a false answer, an unknown answer, and a true answer in the original order.Lumping
M
Median
Membership test
%in% operator.region %in% c("East", "West") retains either named region regardless of its row position.Metacharacter
fixed(".") searches for the punctuation itself instead.Missing-value level
Month rollback
%m+% reaches February 28 in 2026 and February 29 in 2028.N
NaN
NaN; check its count before treating the output as an observed measurement.Nominal category
Numeric bin
cut() places a value equal to an internal break in the lower bin when its default upper-inclusive rule applies.Numeric parsing
parse_number("Mass: 8 kg") returns a number, but the removed unit still matters for interpretation.O
Ordered factor
Ordinal category
P
Pattern detection
str_detect() into filter() to keep names starting with a required prefix in a text column.Pattern extraction
str_extract(), still as text.Period
days(1) can preserve tomorrow's local hour while spanning fewer or more than 24 elapsed hours.Placeholder code
na_if() only when the data documentation identifies it as missing in that column.Q
Quantifier
[0-9]{3}, the class selects digits and the quantifier requires a run of exactly three.Quantile
R
Rank
Raw string
r"(C:\logs)" needs no doubled backslash for R's string-reading layer.Recoding
fct_recode(), put the replacement label on the left and the existing label on the right.Recycling
Regular expression
Run
consecutive_id() assigns a new run number when a status returns after a different status has appeared.S
String
String flattening
summarize(), flattening the member column produces one readable member list for each team.String interpolation
str_glue().Substring
str_sub(code, -3, -1) extracts the final three characters without depending on the code's full length.T
Time of day
Time zone
Time-zone conversion
with_tz() may show the previous date in another zone even though the recorded event has not moved.U
Unicode equivalence
str_equal() can match a composed accented letter to the same letter followed by a combining accent.Unix epoch
as_date(2) advances two days, while as_datetime(2) advances only two seconds.Unused level
.drop = FALSE to show its zero count, or fct_drop() when the category should be removed.V
Vectorized operator
& to combine two column conditions so each row receives its own combined logical result.W
Week start
week_start = 1 consistently when reports define weeks as beginning on Monday.Whitespace
str_squish() turns repeated internal spaces into one space and removes unwanted outer spacing.Word boundary
\b in regex.About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.