17.8 C
London
Sunday, June 22, 2025
HomeStatistics TutorialRHow to Remove NA from Matrix in R (With Example)

How to Remove NA from Matrix in R (With Example)

Related stories

Learn About Opening an Automobile Repair Shop in India

Starting a car repair shop is quite a good...

Unlocking the Power: Embracing the Benefits of Tax-Free Investing

  Unlocking the Power: Embracing the Benefits of Tax-Free Investing For...

Income Splitting in Canada for 2023

  Income Splitting in Canada for 2023 The federal government’s expanded...

Can I Deduct Home Office Expenses on my Tax Return 2023?

Can I Deduct Home Office Expenses on my Tax...

Canadian Tax – Personal Tax Deadline 2022

  Canadian Tax – Personal Tax Deadline 2022 Resources and Tools...

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

Subscribe

- Never miss a story with notifications

- Gain full access to our premium content

- Browse free from up to 5 devices at once

Latest stories