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.
is. check the type of a variable.is.numeric() returns TRUE if the variable is numeric.c("1", "2", "3") to numeric in R?as.numeric() converts data to numeric type.as.numeric(c("1", "2", "3")) converts strings to numbers 1, 2, 3.vec <- c("10", "20", "30")
num_vec <- as.numeric(vec)
is.numeric(num_vec)as.numeric(vec) changes strings "10", "20", "30" to numbers 10, 20, 30.is.numeric(num_vec) returns TRUE because num_vec is numeric.val <- "123abc" num_val <- as.numeric(val) print(num_val)
as.numeric("123abc") cannot convert because of non-numeric characters.NA and shows a warning about NAs introduced by coercion.lst <- list("5", 10, "abc", "15.5"). Which R code correctly converts all elements to numeric, replacing non-convertible values with 0?as.numeric(x) inside a function and check if result is NA.as.numeric(x) is NA, return 0; otherwise return the numeric value.Pass the test and this pattern moves unknown