What is is.na() function in R?

Overview

is.na() is used to deal with missing values in the dataset or data frame. We can use this method to check the NA field in a data frame and help to fill them. To deal with missing values, one's can fill empty fields by NA's using fill.NAs().

Note: We can also use which() function to extract exact indexes of NA values.

Syntax

is.nan(x)


Parameters

It takes the following value as an agument:

x: It can either be a vector or a data frame.

Return value

It returns the boolean or logical value either TRUE or FALSE.

Code

Let’s discuss is.na() function with code examples:

# is.na in r example
x = c(1, 2, NA, 4, NA, 6, 7)
# invoking is.na() to get NA's indexes
print(is.na(x))
# show indexes of NA's
print(which(is.na(x)))

We can also use is.na() to find the missing values in a dataframe and then replace them with new value.

Find missing values.

# Create a vector with missing values
df <- c(1, 2, NA, 4, NA, 6)
# Filter out missing values
new_df <- df[!is.na(df)] # new data frame with no missing values
print(new_df)
# Output: 1 2 4 6

Replace missing values with other values.

df <- c(1, 2, NA, 4, NA, 6)# Replace missing values with 0
df_new<- ifelse(is.na(df), 0, df)
print(df_new)
# Output: 1 2 0 4 0 6

Count the number of missing values.

df <- c(1, 2, NA, 4, NA, 6)
count <- sum(is.na(df))
print(count)

Free Resources