Chapter 8: R Concatenate Elements
R Concatenate Elements” — one of the most frequently used (and sometimes confusing) operations in R.
Concatenate simply means joining / sticking things together, usually strings (text), but also numbers or other elements, to form longer strings or vectors.
In R, there are several ways to do this — each has its personality, best use cases, and little traps. We’ll go through them step by step, like I’m showing you on my screen, with lots of real examples you can copy-paste right now into RStudio.
1. The Two Most Common Functions: paste() and paste0()
These are the workhorses for concatenating in R — you’ll see them in almost every script.
paste() — Joins with a separator (default = space ” “)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Basic examples paste("Hyderabad", "is", "hot", "today") # → "Hyderabad is hot today" (spaces added automatically) paste("Temp:", 29.5, "°C") # → "Temp: 29.5 °C" # Custom separator paste("Aarav", "Priya", "Rahul", sep = " | ") # → "Aarav | Priya | Rahul" paste(1:5, "apple") # → "1 apple" "2 apple" "3 apple" "4 apple" "5 apple" (vectorized!) |
paste0() — Joins without any separator (like paste(…, sep = “”))
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
paste0("file", 1:3, ".csv") # → "file1.csv" "file2.csv" "file3.csv" ← super common for filenames! paste0("Hyderabad", "2026") # → "Hyderabad2026" paste0("Score: ", c(85, 92, 78), "%") # → "Score: 85%" "Score: 92%" "Score: 78%" |
Key arguments both share:
- sep — what to put between each element (only in paste() — paste0() ignores it or treats as “”)
- collapse — if you want all results joined into one single string
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
# Without collapse → vector of strings paste(c("Mon", "Tue", "Wed"), 1:3, sep = "-") # → "Mon-1" "Tue-2" "Wed-3" # With collapse → one long string paste(c("Mon", "Tue", "Wed"), 1:3, sep = "-", collapse = ", ") # → "Mon-1, Tue-2, Wed-3" |
paste0(…, collapse = “, “) is very common when you want a comma-separated list.
2. Quick Comparison Table (Cheat Sheet – Keep This!)
| Function | Default sep | Use when you want… | Typical Example Output | Best For |
|---|---|---|---|---|
| paste() | ” ” (space) | spaces or custom separator between items | “Hello world 2026” | Readable messages, sentences |
| paste0() | “” (nothing) | no space at all, tight joining | “HelloHyderabad2026” or “file1.csv” | Filenames, codes, keys, no-gap strings |
| paste(…, collapse=) | — | turn many pieces into one string | “item1, item2, item3” | CSV lists, logging |
Rule of thumb 2026:
- Want spaces or punctuation between parts? → paste()
- Want nothing between (filenames, numbers+text tight)? → paste0()
- Want final single string with commas? → add collapse = “, “
3. Even More Powerful: sprintf() (C-style formatting)
sprintf() lets you insert values into a template string — very clean for messages/reports.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
# Basic placeholders: %s = string, %d = integer, %f = float sprintf("Today in %s it's %.1f°C with %d%% humidity", "Hyderabad", 29.5, 62) # → "Today in Hyderabad it's 29.5°C with 62% humidity" # Vectorized too! sprintf("Student %d: %s scored %.1f%%", 1:3, c("Aarav", "Priya", "Rahul"), c(92.3, 85.0, 78.5)) # → "Student 1: Aarav scored 92.3%" ... |
Common placeholders:
- %s → string/character
- %d → integer
- %f → floating point (use %.1f for 1 decimal)
- %e → scientific notation
Very useful in reports, file names, logging.
4. Other Ways You Might See (Less Common but Useful)
- cat() — concatenates and prints immediately (no return value)
|
0 1 2 3 4 5 6 7 |
cat("Average =", mean(c(78,92,85)), "%\n") # prints: Average = 85 % |
- paste() inside cat() for complex messages
|
0 1 2 3 4 5 6 |
cat(paste("File", 1:3, "processed", sep = "_"), sep = " → ") |
- Modern tidyverse way (2026 favorite for many): glue::glue()
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 |
# install.packages("glue") once library(glue) name <- "Webliance" score <- 92.7 glue("Hello {name}! Your score is {score}% 🎉") # → "Hello Webliance! Your score is 92.7% 🎉" |
glue() is very readable — many people prefer it now over paste/sprintf.
5. Your Mini Practice Right Now (Copy → Run!)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Setup city <- "Hyderabad" temp <- 29.8 foods <- c("Biryani", "Haleem", "Irani Chai") days <- c("Mon", "Tue", "Wed") temps <- c(28.5, 30.2, 29.1) # Different styles – compare outputs! paste("Welcome to", city, "! Temp:", temp, "°C") # spaces paste0(city, temp, "°C today") # no space paste0("file_", 1:3, ".csv") # filenames # One long string paste(foods, collapse = ", ") # "Biryani, Haleem, Irani Chai" # sprintf style sprintf("In %s on %s it was %.1f°C", city, days, temps) # glue style (if you have glue package) # library(glue) # glue("{city} forecast: {paste(days, temps, sep='=', collapse=' | ')}") |
6. Common Beginner Mistakes & Fixes
- Forgetting collapse when you want one string → get many separate strings instead
- Using paste() when you want no space → extra spaces appear
- Mixing types without thinking → R converts to character automatically (usually fine)
- sep vs collapse confusion → sep = between arguments, collapse = join final result
Summary from Your Teacher
- Everyday work: paste() (with space) or paste0() (no space)
- Need one final string? Add collapse = “, ” or similar
- Fancy formatting / reports? → sprintf() or glue()
- Just want to print nicely? → cat(paste0(…))
Want to go deeper?
- Practice building file name lists / report titles together?
- Compare glue vs base in detail?
- Or next topic (vectors deeper, subsetting, data frames)?
Just tell me — whiteboard is clean and ready! ☕🚀
