0
0
R Programmingprogramming~5 mins

Type checking and conversion in R Programming

Choose your learning style9 modes available
Introduction

Type checking helps you know what kind of data you have. Conversion changes data from one type to another so you can work with it easily.

When you want to make sure a number is really a number before doing math.
When you get data as text but need to use it as a number.
When you want to check if a value is a list or a single item.
When you need to change data types to fit a function's needs.
When cleaning data that comes from different sources with mixed types.
Syntax
R Programming
is.type(x)

as.type(x)

is.type(x) checks if x is of a certain type, like is.numeric(x).

as.type(x) converts x to a type, like as.character(x) to make it text.

Examples
Check if x is a number. This returns TRUE because 5 is numeric.
R Programming
x <- 5
is.numeric(x)
Convert text "123" to number 123 so you can do math with it.
R Programming
y <- "123"
as.numeric(y)
Convert decimal number 3.14 to integer 3 by dropping the decimal part.
R Programming
z <- 3.14
as.integer(z)
Check if a is a logical (TRUE or FALSE) value.
R Programming
a <- TRUE
is.logical(a)
Sample Program

This program starts with x as text "42". It checks if x is numeric (it is not). Then it converts x to a number and checks again. Finally, it adds 8 to the number and shows the result.

R Programming
x <- "42"
cat("Is x numeric?", is.numeric(x), "\n")
num_x <- as.numeric(x)
cat("After conversion, is x numeric?", is.numeric(num_x), "\n")
cat("x plus 8 equals", num_x + 8, "\n")
OutputSuccess
Important Notes

When converting text to numbers, if the text is not a valid number, R will return NA (missing value).

Type checking functions start with is. like is.character(), is.integer(), is.logical().

Conversion functions start with as. like as.numeric(), as.character(), as.logical().

Summary

Use is.type() functions to check what kind of data you have.

Use as.type() functions to change data from one type to another.

Type checking and conversion help avoid errors and make your code work smoothly.