R Easy · Lesson 1 · On the house

Strings and paste

paste, paste0, sprintf, nchar, substr. Lesson 1 is free — on the house.

Lessons · R Easy · Lesson 1 of 10 · On the house

Strings and paste

paste, paste0, sprintf, nchar, substr.

Illustration for R
Lesson 1 is on the house.

paste(..., sep = " ") joins arguments with a separator (default space). paste0(...) is paste with sep = "" — the everyday way to glue without spaces. Both recycle shorter arguments to the longest length.

sprintf("score=%d", 95) formats like C: %d integer, %f/%.2f floating, %s string. Prefer sprintf when you need aligned numeric formatting; prefer paste0 for simple concatenation.

nchar(x) counts characters in each string (NA stays NA). substr(x, start, stop) extracts inclusive character positions (1-based). toupper / tolower change case; they work elementwise on character vectors.

strsplit(x, split) returns a list of character vectors — one per input string. strsplit("a,b,c", ",")[[1]] is c("a", "b", "c"). The split can be a fixed string or a regex (fixed = TRUE to disable regex).

Misses: calling join like Python, using + to concatenate strings, treating strsplit as returning an atomic vector, or 0-based substr indexes.

strings

names <- c("Ada", "Gus")
roles <- c("author", "reader")
print(paste(names, roles, sep = ":"))
print(paste0(names, "=", roles))
print(sprintf("%s scored %d", "Ada", 95))
print(nchar(names))
print(substr(names, 1, 2))
print(toupper(names[1]))
parts <- strsplit("a,b,c", ",")[[1]]
print(parts)
Match this when you type.

Quiz

What is paste0(...) equivalent to?

Quiz

What does strsplit("a,b,c", ",") return?

Quiz

Are substr indexes 0-based or 1-based?

Quiz

Which formats an integer into a string like C?

Check

Match the still for: Strings and paste.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.