Character — Working with Text
Text in R lives in character vectors written in quotes, and functions such as paste(), nchar(), substr() and toupper() join, measure, cut and change it.
Transform and compare character values while preserving the intended encoding and meaning.
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.