How to Replace Inf Values with NA in R

Replace Inf Values with NA in R, you can substitute NA values for Inf values using the techniques listed below:

Method 1: Replace Inf with NA in Vector

x[is.infinite(x)] <- NA

Example 1: Substitute NA for Inf in the Vector

The code below demonstrates how to swap out all Inf values in a vector for NA values.

x <- c(14, 102, Inf, 8, Inf, 9, 12, 3, 202, Inf)
x[is.infinite(x)] <- NA
x
[1] 14 102 NA 8 NA 9 12 3 202 NA

You’ll see that the original vector’s Inf values have all been swapped out for NA values.

How to Find Quartiles in R? – Data Science Tutorials

Method 2: Replace Inf with NA in All Columns of the Data Frame

df[sapply(df, is.infinite)] <- NA

Example 2: Change all columns in the data frame from Inf to NA

In every column of a data frame, Inf values can be changed to NA values using the code below:

Let’s create a data frame

df <- data.frame(x=c(14, 15, 25, 34, Inf, 18, Inf),
                 y=c(10, Inf, Inf, 43, 45, 55, 88),
                 z=c(Inf, 55, 45, 65, 35, 102, 14))
df
   x   y   z
1  14  10 Inf
2  15 Inf  55
3  25 Inf  45
4  34  43  65
5 Inf  45  35
6  18  55 102
7 Inf  88  14

Now we can replace Inf values with NA values in all columns

Algorithm Classifications in Machine Learning – Data Science Tutorials

df[sapply(df, is.infinite)] <- NA
df
  x  y   z
1 14 10  NA
2 15 NA  55
3 25 NA  45
4 34 43  65
5 NA 45  35
6 18 55 102
7 NA 88  14

Observe that NA values have been substituted for the Inf values in each column of the data frame.

Method 3: Replace Inf with NA in Specific Columns of the Data Frame

df[c('col1', 'col2')][sapply(df[c('col1', 'col2')], is.infinite)] <- NA

Example 3: In certain columns of a data frame, replace Inf with NA

The code below demonstrates how to change Inf values in particular columns of a data frame to NA values.

Boosting in Machine Learning:-A Brief Overview (datasciencetut.com)

Now let’s create a data frame

df <- data.frame(x=c(44, 55, 15, 34, Inf, 88, Inf),
                 y=c(110, Inf, Inf, 33, 55, 58, 88),
                 z=c(Inf, 75, 85, 6, 33, 12, 114))
df
   x   y   z
1  44 110 Inf
2  55 Inf  75
3  15 Inf  85
4  34  33   6
5 Inf  55  33
6  88  58  12
7 Inf  88 114

Now replace Inf values with NA values in columns ‘x’ and ‘z’ only

df[c('x', 'z')][sapply(df[c('x', 'z')], is.infinite)] <- NA
df
   x   y   z
1 44 110  NA
2 55 Inf  75
3 15 Inf  85
4 34  33   6
5 NA  55  33
6 88  58  12
7 NA  88 114

The NA values have been substituted for the Inf values in the ‘x’ and ‘y’ columns, as you can see.

The Inf values in column ‘y’ have not changed, nevertheless.

Replace NA with Zero in R – Data Science Tutorials

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

six + 20 =