To represent infinity numbers in R, you can use the “Inf” and “-Inf”.
The Inf and -Inf are positive and negative infinity, whereas NaN means “Not a Number”.
Positive Infinity
positive_infinity <- Inf
print(positive_infinity)
Output
[1] Inf
Negative Infinity
negative_infinity <- -Inf
print(negative_infinity)
Output
[1] -Inf
The Inf is helpful in scenarios such as setting initial values in optimization problems (where you might want to start with an infinitely large or small value) or handling overflow in computations.
Creating infinity programmatically
vec <- 21
div <- vec / 0
div
Output
[1] Inf
How to Handle Infinity
To handle the infinity , you can use the “is.infinite()” or “is.finite()” function.
is.infinite()
The is.infinite() function is used to check if the vector contains infinite values as elements.
data <- 21
div <- data / 0
is.infinite(div)
Output
[1] TRUE
is.finite()
The is.finite() function is used to check if the elements of a vector are finite values or not.
data <- 21
div <- data / 0
is.finite(div)
Output
[1] FALSE
Since the value is infinity, is.finite() function returns FALSE.
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.