R Type Conversion
Type Conversion
Sometimes you need to change a value from one data type to another. This is called type conversion.
For example, numbers that come from a file or a form are often stored as text. A number in quotes is a string, so R cannot do math with it:
Example
age <- "25"
age + 1
Result:
Error in age + 1 : non-numeric argument to binary operatorTry it Yourself »
To get the right result, you need to know how type conversion works.
There are two types of conversion in R:
- Implicit conversion (automatically)
- Explicit conversion (manually)
Implicit Conversion
R converts some values automatically, when you combine different types in a calculation.
If you add an integer and a numeric value, R converts the result to numeric, so the decimals are not lost:
Example
x <- 5L + 2.5
x
class(x)
Try it Yourself »
Logical values are also converted automatically: TRUE becomes 1, and FALSE becomes 0:
Example
TRUE + 5
FALSE + 5
Try it Yourself »
Note: R never converts a string to a number automatically. That is why "25" + 1 gives an error. You must convert it yourself.
Explicit Conversion
To convert a value yourself, use one of these functions:
| Function | Converts to |
|---|---|
| as.numeric() | numeric (a number, with or without decimals) |
| as.integer() | integer (a whole number) |
| as.character() | character (a string) |
| as.logical() | logical (TRUE or FALSE) |
Now we can fix the problem from the start of this page:
Example
age <- "25"
age <- as.numeric(age)
age + 1
Try it Yourself »
Convert Between Number Types
You can also convert between the number types from the R Numbers chapter:
Example
x <- 1L # integer
y <- 2 # numeric
# convert from integer to numeric:
a <- as.numeric(x)
# convert from numeric to integer:
b <- as.integer(y)
# print values of x and y
x
y
# print the class name of a and b
class(a)
class(b)
Try it Yourself »
Decimals Are Removed
Be careful when you convert a number with decimals to an integer. as.integer() does not round the number. It just removes the decimals:
Example
x <- 9.99
as.integer(x)
round(x)
Try it Yourself »
What happened to .99? It is gone! If you want the nearest whole number, use round() from the R Math chapter instead.
Convert to a String
Use as.character() to convert a number to a string:
Example
x <- 10
y <- as.character(x)
y
class(y)
Try it Yourself »
The result has quotes around it, because it is now text.
When Conversion Fails
If R cannot convert a value, it gives NA (a missing value) and shows a warning:
Example
x <- as.numeric("hello")
Result:
Warning message: NAs introduced by coercionTry it Yourself »
You will learn more about NA in the R Missing Values chapter, and about warnings in the R Errors chapter.
Real-Life Example
A web shop stores the price and the quantity as text. To find the total price, convert both values to numbers first:
Example
price <- "19.99"
quantity <- "3"
total <- as.numeric(price) * as.numeric(quantity)
total
Try it Yourself »