R Conversions
A conversion changes a value from one type to another. R names each conversion with the type it builds.
Converting text to numbers
Each print changes a value to a new type. Text becomes numbers and a number becomes text.
print(as.integer("42"))
print(as.numeric("4.5"))
print(as.character(42))Converting to logical values
The first two prints change numbers to logical values. The last print changes TRUE to the number 1.
print(as.logical(1))
print(as.logical(0))
print(as.numeric(TRUE))Cutting off a fraction
as.integer cuts the fraction from 3.99 and leaves 3. class shows the type of the new value.
value <- as.integer(3.99)
print(value)
print(class(value))Example
x <- as.numeric("4.5")
print(x)
print(as.integer(x))
print(class(x))Key points
- as.integer changes a value to a whole number.
- as.numeric changes a value to a number that can hold decimals.
- as.character changes a value to text.
- as.logical changes a value to TRUE or FALSE.
- as.integer cuts off the fraction of a decimal value.
- The cut in as.integer is not rounding.
- class shows the type of a converted value.
In this example, the text "4.5" becomes the number 4.5. as.integer then cuts the value to 4. class confirms the first value is numeric.
Note
A text value with no number in it converts to NA with a warning.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท rdrr.io R Snippets
Exercise
What does print(as.integer(3.99)) show?