Types and Missing Values
Type Conversion
Text to Numbers
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 = "")
raw ← 10, 12, 15
1raw <- c("10", "12", "15")2numbers <- as.numeric(raw)values this step10, 12, 15rawnumbers ← 10, 12, 15
1raw <- c("10", "12", "15")2numbers <- as.numeric(raw)3total <- sum(numbers)values this step10, 12, 15numbers10, 12, 15rawtotal ← 37
2numbers <- as.numeric(raw)3total <- sum(numbers)4cat(total, "\n", sep = "")values this step37total10, 12, 15numberscat(total, " ", sep = "")
3total <- sum(numbers)4cat(total, "\n", sep = "")output37values this step37total
Follow the Conversion
rawstarts as text values:"10","12", and"15".as.numeric(raw)converts them to numbers.numbersbecomes10,12, and15.sum(numbers)adds them to get37.catprints37. | 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.