0 votes
1 view
in R Programming by (5.3k points)
edited by

I have a data.frame containing some columns with all NA values, how can I delete them from the data.frame.

Can I use the function

na.omit(...) 

specifying some additional arguments?

1 Answer

0 votes
by (25.3k points)

To delete columns that contain only NAs, you can use the following code:

set.seed <- 100

df <- data.frame( id = 1:10 , nas = rep( NA , 10 ) , vals = sample( c( 1:3 , NA ) , 10 , repl = TRUE ) )

df

   id nas vals

1   1  NA    3

2   2  NA    2

3   3  NA    1

4   4  NA   NA

5   5  NA    3

6   6  NA    2

7   7  NA    3

8   8  NA   NA

9   9  NA    3

10 10  NA   NA

> df[, colSums(is.na(df)) != nrow(df)]

   id vals

1   1    3

2   2    2

3   3    1

4   4   NA

5   5    3

6   6    2

7   7    3

8   8   NA

9   9    3

10 10   NA

Related questions

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...