manoj manoj - 28 days ago 6
R Question

R - Delete column if last value is NA

I want to delete column(s) in R data frame if their last value is NA.

Example data frame is below

A B C D
11 10 19 20
22 20 29 40
33 30 39 60
44 NA NA 80


I would like to get the following output (Column B and C dropped because they had NA values in the last row)

A D
11 20
22 40
33 60
44 80


Tried but couldn't get any solution to work. Appreciate your help.

Answer
# Data
df <- read.table(text="A   B   C   D
                       11  10  19  20
                       22  20  29  40
                       33  30  39  60
                       44  NA  NA  80", header=TRUE)

df[-which(is.na(df[nrow(df), ]))]

   A  D
1 11 20
2 22 40
3 33 60
4 44 80

# Suggestion from @alistaire
df[, !is.na(df[nrow(df), ])]