R — Atomic types and integer vectors
Character and integer are different atomic types in R. Use a character value for a label and integer values for quantities used in arithmetic.
A simple example
Tell a number from text
- Start with 2 and "2"
- Do this Add or join
- Result 4 and 22
cat(2 + 2, "\n", sep = "")
cat(paste0("2", "2"), "\n", sep = "")
4 22
Choosing a data type
| Type or declaration | Example | Use |
|---|---|---|
| character | "007" |
A length-one character vector keeps the printed code. |
| integer | 125L |
The L suffix requests integer storage. |
| double | 125 |
An ordinary numeric literal without L has double storage. |
| logical | TRUE |
Used in conditions. Logical vectors can contain NA. |
| typed missing value | NA_integer_ |
Marks a missing integer. Use is.na to check for missing values. |
Keep a product identifier and its price distinct
Keep the printed code 007 as text. Store the quantity and the price in cents as whole numbers so multiplication gives an exact total for this order. The L suffix creates an integer literal. Without it, an ordinary numeric literal generally has type double. Combining unlike values into one atomic vector can coerce them to a common type.
A school shop sells three packs of paper at 125 cents each. Its scanner must print the code 007 exactly as it appears on the shelf. Keep the code as text and multiply the numeric quantity and price.
Run the example
Use R 4.x. Run these commands from the directory containing the example.
Rscript --vanilla Lesson.R
product <- "007"
quantity <- 3L
price_cents <- 125L
total <- quantity * price_cents
cat(sprintf("%s: %d cents\n", product, total))
007: 375 cents
The label retains both leading zeros. Three units at 125 cents cost 375 cents. The display joins the values only after the calculation.
Try it yourself
Change the code to 010 and the quantity to zero. What should stay visible?
Check your answer
The label stays 010 and the total becomes 0 cents. Treating the identifier as a number would lose its written form.