Concept Flow - Type checking and conversion
Start with a variable
Check variable type
Is type correct?
No→Convert type
Variable now new type
Use variable
This flow shows how R checks a variable's type and converts it if needed before using it.
x <- "123" typeof(x) x_num <- as.numeric(x) typeof(x_num)
| Step | Code executed | Variable | Type before | Action | Type after | Output |
|---|---|---|---|---|---|---|
| 1 | x <- "123" | x | NULL | Assign string "123" | character | |
| 2 | typeof(x) | x | character | Check type | character | "character" |
| 3 | x_num <- as.numeric(x) | x_num | NULL | Convert x to numeric | double | |
| 4 | typeof(x_num) | x_num | double | Check type | double | "double" |
| Variable | Start | After Step 1 | After Step 3 | Final |
|---|---|---|---|---|
| x | NULL | "123" | "123" | "123" |
| x_num | NULL | NULL | 123 | 123 |
Type checking in R uses typeof() to find a variable's type. Conversion uses functions like as.numeric() to change types. Original variables keep their type unless reassigned. Always check type before and after conversion to avoid errors.