R values have types. Data often arrives as text, then gets converted before numeric functions can use it.

Program

Play the script to watch character values become numbers and then a total.

type_conversion.R
Replay: real traced execution (multi-file project)
raw <- c("10", "12", "15")
numbers <- as.numeric(raw)
total <- sum(numbers)
cat(total, "\n", sep = "")
  1. raw ← 10, 12, 15

    1raw <- c("10", "12", "15")2numbers <- as.numeric(raw)
    values this step10, 12, 15raw
  2. numbers ← 10, 12, 15

    1raw <- c("10", "12", "15")2numbers <- as.numeric(raw)3total <- sum(numbers)
    values this step10, 12, 15numbers10, 12, 15raw
  3. total ← 37

    2numbers <- as.numeric(raw)3total <- sum(numbers)4cat(total, "\n", sep = "")
    values this step37total10, 12, 15numbers
  4. cat(total, " ", sep = "")

    3total <- sum(numbers)4cat(total, "\n", sep = "")
    output37
    values this step37total

Follow the Conversion

  1. raw starts as text values: "10", "12", and "15".
  2. as.numeric(raw) converts them to numbers.
  3. numbers becomes 10, 12, and 15.
  4. sum(numbers) adds them to get 37.
  5. cat prints 37. | raw text | numeric value | | --- | --- | | "10" | 10 | | "12" | 12 | | "15" | 15 |
character vector Quoted values such as `"10"` are text, even when they look numeric.
as.numeric `as.numeric` converts compatible text values to numeric values.
type conversion Conversion changes how later functions interpret the value.

Exercise: type_conversion.R

Reproduce the printed total 37, then change one raw text number and predict the new total before running it.