Reuben Mathew
Reuben Mathew

Reputation: 598

Delete column with NAs in first row

If I have a dataframe like so

a <- c(NA,1,2,NA,4)
b <- c(6,7,8,9,10)
c <- c(NA,12,13,14,15)
d <- c(16,NA,18,NA,20)
df <- data.frame(a,b,c,d)

How can I delete columns "a" and "c" by asking R to delete those columns that contain an NA in the first row?

My actual dataset is much bigger, and this is only by way of a reproducible example.

Please note that this isn't the same as asking to delete columns with any NAs in it. My columns may have other NA values in it. I'm looking to delete just the ones with an NA in the first row.

Upvotes: 1

Views: 408

Answers (1)

Heroka
Heroka

Reputation: 13139

You can use a vector of booleans indicating wether the first row is missing in this case.

res <- df[,!is.na(df[1,])]

> res
   b  d
1  6 16
2  7 NA
3  8 18
4  9 NA
5 10 20

Upvotes: 6

Related Questions