1

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.

manoj
  • 71
  • 1
  • 7

2 Answers2

3
# 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), ])]
JasonWang
  • 2,414
  • 11
  • 12
0

na.omit() function deletes any rows with missing data. pp <- data.frame(po=c(10,20,30,40,NA), pi=c(45,65,75,55,85)) pp na.omit(pp) -- deletes the entire row

na.delete(pp["po"]) --- deletes the entire column with "NA".

Mahendra
  • 19
  • 2
  • This is true, but the OP needs to test if *the last row* is `NA` and only delete the column in that case. This answer will delete if the `NA` occurs anywhere. – Gregor Thomas Nov 12 '16 at 07:37