3

I have a data frame where only some of the rows have all NA. How do I loop through and delete all these rows? I tried na.omit() but that doesn't work. In this example I need rows 3 and 5 removed

x1 <- c("Bob", "Mary","","Jane","")
x2 <- c("Bob","Mary","","Jane","")
x3 <- c("Bob", "Mary","","Jane","")
x4 <- c("Bob","Mary","","Jane","")

df <- data.frame(x1,x2,x3,x4)

df <- df %>% na.omit()
Val
  • 55
  • 1
  • 4
  • That contains zero `NA` ... though based on your description, @gos' suggestion is the answer: `complete.cases`. – r2evans Jul 06 '18 at 16:29

2 Answers2

8

Here is one option; first you need to define the NA pattern.

df[df == ""] <- NA # define NA pattern
df[rowSums(is.na(df)) != ncol(df), ] # result
# Try with x1 <- c("Bob", "Mary","","","") 
nghauran
  • 6,648
  • 2
  • 20
  • 29
3
> df[rowSums(df=="")!=ncol(df), ]
    x1   x2   x3   x4
1  Bob  Bob  Bob  Bob
2 Mary Mary Mary Mary
4 Jane Jane Jane Jane
Jilber Urbina
  • 58,147
  • 10
  • 114
  • 138
  • 2
    While this answer is probably correct and useful, it is preferred if you include some explanation along with it to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. – Erty Seidohl Jul 06 '18 at 19:04