Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove only rows that have all NA in R? [duplicate]

Tags:

loops

r

na

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()
like image 718
Val Avatar asked Jan 20 '26 14:01

Val


1 Answers

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","","","") 
like image 157
nghauran Avatar answered Jan 23 '26 07:01

nghauran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!