R How to Convert Data Types with Examples
as.numeric(), as.character(), as.factor(), and as.logical() to change a value's type.Examples
How to Think About It
as.numeric() for numbers or as.character() for text. This changes the data's form so R treats it correctly.Algorithm
Code
x <- "42" num_x <- as.numeric(x) char_x <- as.character(num_x) factor_x <- as.factor(c("apple", "banana", "apple")) print(num_x) print(char_x) print(factor_x)
Dry Run
Let's trace converting a string "42" to numeric and back to character, then creating a factor.
Convert string to numeric
Input: "42" -> as.numeric("42") = 42
Convert numeric to character
Input: 42 -> as.character(42) = "42"
Create factor from character vector
Input: c("apple", "banana", "apple") -> as.factor(...) creates factor with levels apple and banana
| Step | Input | Output |
|---|---|---|
| 1 | "42" | 42 (numeric) |
| 2 | 42 | "42" (character) |
| 3 | c("apple", "banana", "apple") | factor with levels apple, banana |
Why This Works
Step 1: Use as.numeric() to convert text to number
The as.numeric() function changes a character string that looks like a number into an actual numeric value R can calculate with.
Step 2: Use as.character() to convert number to text
The as.character() function turns numbers into strings so R treats them as text.
Step 3: Use as.factor() to create categorical data
The as.factor() function converts a vector of strings into a factor, which R uses to represent categories with levels.
Alternative Approaches
x <- "123" converted <- type.convert(x, as.is = TRUE) print(converted)
x <- "42" int_x <- as.integer(x) print(int_x)
Complexity: O(n) time, O(n) space
Time Complexity
Conversion functions process each element once, so time grows linearly with data size.
Space Complexity
Conversions create new objects of the same size, so space usage is proportional to input size.
Which Approach is Fastest?
Direct functions like as.numeric() are fast and clear; type.convert() is convenient but slightly slower due to type guessing.
| Approach | Time | Space | Best For |
|---|---|---|---|
| as.numeric()/as.character()/as.factor() | O(n) | O(n) | Explicit, clear conversions |
| type.convert() | O(n) | O(n) | Automatic type detection |
| as.integer() | O(n) | O(n) | Integer-specific conversion |
class() after conversion to confirm it changed as expected.as.numeric() results in NA and a warning.