Replace Inf with NA in Vector & Data Frame in R (Example)
In this R tutorial you’ll learn how to clean Inf values from your data.
The article is structured as follows:
- Example 1: Replace Inf by NA in Vector
- Example 2: Replace Inf by NA in Data Frame
- Video & Further Resources
Let’s dive into it!
Example 1: Replace Inf by NA in Vector
Example 1 shows how to remove infinite values from a vector or array in R. First, let’s create such a vector:
my_vec <- c(1, 7, 3, Inf, 5, Inf) # Create example vector my_vec # Print example vector # 1 7 3 Inf 5 Inf
Our example vector contains six elements, whereby two of these elements are infinite (i.e. Inf).
Now, we can use the is.infinite function to identify these infinite values and replace them by NA:
my_vec[is.infinite(my_vec)] <- NA # Replace Inf in vector by NA my_vec # Print updated vector # 1 7 3 NA 5 NA
The previously shown output of the RStudio console shows that our updated vector contains NA values at the positions of Inf in our original vector.
Example 2: Replace Inf by NA in Data Frame
Example 2 explains how to replace Inf values in a data frame with NA. Again, we need to create some example data:
my_data <- data.frame(x1 = c(Inf, 2, 3, 4, 5), # Create example data frame x2 = c(1, Inf, 1, Inf, 1)) my_data # Print example data frame # x1 x2 # 1 Inf 1 # 2 2 Inf # 3 3 1 # 4 4 Inf # 5 5 1
Our data table consists of five rows and two columns. Both of our variables contain at least one Inf value.
If we want to clean these infinite values, we can use a combination of the do.call, data.frame, lapply, replace, and is.infinite functions. Have a look at the following R code and its output:
my_data <- do.call(data.frame, # Replace Inf in data by NA lapply(my_data, function(x) replace(x, is.infinite(x), NA))) my_data # Print updated data frame # x1 x2 # 1 NA 1 # 2 2 NA # 3 3 1 # 4 4 NA # 5 5 1
As you can see, we changed the Inf values in all columns to NA.
Video & Further Resources
Have a look at the following video which I have published on my YouTube channel. In the video, I show the contents of this tutorial:
Please accept YouTube cookies to play this video. By accepting you will be accessing content from YouTube, a service provided by an external third party.
If you accept this notice, your choice will be saved and the page will refresh.
In addition, you could read the other articles which I have published on my website. A selection of tutorials is listed here.
- Replace 0 with NA in R
- Replace Particular Value in Data Frame
- The do.call R Function
- The R Programming Language
In summary: You learned in this tutorial how to exchange infinite values by not available values in an array or a data matrix in the R programming language. Let me know in the comments section below, if you have any further questions. Furthermore, please subscribe to my email newsletter in order to receive regular updates on the newest posts.
Statistics Globe Newsletter