*35*

You can use the following methods to remove NA values from a matrix in R:

**Method 1: Remove Rows with NA Values**

new_matrix !rowSums(is.na(my_matrix)),]

**Method 2: Remove Columns with NA Values**

new_matrix !colSums(is.na(my_matrix))]

The following examples show how to use each method in practice with the following matrix in R:

#create matrix my_matrix 4) #view matrix my_matrix [,1] [,2] [,3] [1,] NA 7 9 [2,] 0 4 5 [3,] NA 1 5 [4,] 5 3 8

**Method 1: Remove Rows with NA Values**

The following code shows how to remove all rows from the matrix that contain NA values:

#remove all rows with NA values new_matrix !rowSums(is.na(my_matrix)),] #view updated matrix new_matrix [,1] [,2] [,3] [1,] 0 4 5 [2,] 5 3 8

Notice that all rows with NA values have been removed from the matrix.

**Related:** How to Use rowSums() Function in R

**Method 2: Remove Columns with NA Values**

The following code shows how to remove all columns from the matrix that contain NA values:

#remove all columns with NA values new_matrix !colSums(is.na(my_matrix))] #view updated matrix new_matrix [,1] [,2] [1,] 7 9 [2,] 4 5 [3,] 1 5 [4,] 3 8

Notice that all columns with NA values have been removed from the matrix.

**Related:** How to Use colSums() Function in R

**Bonus: Convert NA Values to Zero in Matrix**

If you simply want to convert all NA values to zero in a matrix, you can use the following syntax:

#remove all columns with NA values my_matrix[is.na(my_matrix)] #view updated matrix my_matrix [,1] [,2] [,3] [1,] 0 7 9 [2,] 0 4 5 [3,] 0 1 5 [4,] 5 3 8

Notice that all NA values have been converted to zero.

**Additional Resources**

The following tutorials explain how to perform other common operations with missing values in R:

How to Remove NA Values from Vector in R

How to Find and Count Missing Values in R

How to Impute Missing Values in R