Character — Working with Text
The newsletter needs labels like "Plot A: 12.5 kg", and the crop names arrive in lower case when the chart wants capitals. Text in R is its own type, character, with a small set of functions that cover most everyday jobs.
The rule
Text lives in quotes;
paste()joins,nchar()counts,substr()cuts.
A character value is written in double or single quotes; both mean the same thing. Like everything in R, text comes in vectors:
plot <- c("A", "B", "C", "D", "E")
crop <- c("tomato", "bean", "tomato", "chilli", "bean")
typeof(crop) # "character"
length(crop) # 5, the number of elements
nchar(crop) # 6 4 6 6 4, letters in each element
toupper(crop[4]) # "CHILLI"
substr("tomato", 1, 3) # "tom", characters 1 to 3Joining text is paste()'s job, and it has two knobs:
paste("Plot", plot) # "Plot A" "Plot B" ... one per element
paste("Plot", plot, sep = "-") # "Plot-A" "Plot-B" ...
paste0("plot_", plot) # "plot_A" ... paste0 uses no separator
paste(crop, collapse = ", ") # "tomato, bean, tomato, chilli, bean"sepgoes between the arguments inside each result. The default is a space.collapsesquashes a whole vector into one string.
For numbers with a fixed format, sprintf() is tidier: sprintf("%s: %.1f kg", plot, c(12.5, 8, 15, 3.5, 6)) gives "A: 12.5 kg", "B: 8.0 kg" and so on, with %.1f meaning "one decimal place".
Special characters use a backslash: "\n" is a new line, "\t" a tab, and "She said \"ripe\"" puts quotes inside a string. print() shows those backslashes; cat() shows the text as a reader would see it.
Text is not a number, even if it looks like one. "12" + 1 is an error: non-numeric argument to binary operator. Convert it first, which is what the Type Conversion lesson is about.
The shortcut
Two confusions cause most text bugs, and one question settles each:
- Counting: "elements or letters?" Elements is
length(), letters isnchar(). - Joining: "between pieces or into one?" Between pieces is
sep, into one iscollapse.
Pick the element
crop[4]is "chilli".
Drills
Answer fast — trust the rule.
What is length("chilli")?
What is substr("tomato", 3, 5)?
What does paste("Plot", "A", sep = "-") return?
What does paste(c("A", "B"), collapse = "+") return?
What happens when you run "12" + 1?
Remember
- Text lives in quotes;
paste()joins,nchar()counts,substr()cuts. - Shortcut: elements or letters,
length()ornchar(); between pieces or into one,seporcollapse. - Trap: text that looks like a number is still text.
