How to Remove Columns with NA Values in R - Statology (2024)

Posted on by Zach

You can use one of the following two methods to remove columns from a data frame in R that contain NA values:

Method 1: Use Base R

df[ , colSums(is.na(df))==0]

Method 2: Use dplyr

library(dplyr)df %>% select_if(~ !any(is.na(.)))

Both methods produce the same result.

The following examples show how to use each method in practice with the following data frame:

#create data framedf <- data.frame(team=c('A', 'B', 'C', 'D', 'E'), points=c(99, NA, NA, 88, 95), assists=c(33, 28, 31, 39, 34), rebounds=c(30, 28, 24, 24, NA))#view data framedf team points assists rebounds1 A 99 33 302 B NA 28 283 C NA 31 244 D 88 39 245 E 95 34 NA

Example 1: Remove Columns with NA Values Using Base R

The following code shows how to remove columns with NA values using functions from base R:

#define new data framenew_df <- df[ , colSums(is.na(df))==0]#view new data framenew_df team assists1 A 332 B 283 C 314 D 395 E 34

Notice that the two columns with NA values (points and rebounds) have both been removed from the data frame.

Example 2: Remove Columns with NA Values Using dplyr

The following code shows how to remove columns with NA values using functions from the dplyr package:

library(dplyr)#define new data framenew_df <- df %>% select_if(~ !any(is.na(.)))#view new data framenew_df team assists1 A 332 B 283 C 314 D 395 E 34

Once again, the two columns with NA values (points and rebounds) have both been removed from the data frame.

Additional Resources

The following tutorials explain how to perform other common tasks in R:

How to Add a Column to a Data Frame in R
How to Rename Data Frame Columns in R
How to Sort a Data Frame by Column in R

How to Remove Columns with NA Values in R - Statology (2024)
Top Articles
Latest Posts
Article information

Author: Reed Wilderman

Last Updated:

Views: 5630

Rating: 4.1 / 5 (72 voted)

Reviews: 95% of readers found this page helpful

Author information

Name: Reed Wilderman

Birthday: 1992-06-14

Address: 998 Estell Village, Lake Oscarberg, SD 48713-6877

Phone: +21813267449721

Job: Technology Engineer

Hobby: Swimming, Do it yourself, Beekeeping, Lapidary, Cosplaying, Hiking, Graffiti

Introduction: My name is Reed Wilderman, I am a faithful, bright, lucky, adventurous, lively, rich, vast person who loves writing and wants to share my knowledge and understanding with you.