Detect empty cells in rows with multiple columns and remove them in r

Viewed 34

I want to find all the empty rows in specific columns and then remove them. I was able to do so:

#specify which one is empty in gender, education level,and industry
which(msUS$Gender =="",arr.ind = TRUE)
which(msUS$Education_Level=="",arr.ind = TRUE)
which(msUS$Industry=="",arr.ind = TRUE)
#remove the empty rows
msUS <-msUS[!(msUS$Gender==""),]
msUS <-msUS[!(msUS$Education_Level==""),]
msUS <-msUS[!(msUS$Industry==""),]
#check num of rows & columns

Is there any smarter way to do it?

1 Answers

If we want to do this on another way, instead of which with arr.ind performed on single column, create a logical matrix with the selected columns, and then check the count of blank ("") in each row with rowSums, and then select only rows having no blanks (==0)

myUS[rowSums(myUS[c("Gender", "Education_Level", "Industry")] == "") == 0,]

Another option is if_any with filter from dplyr

library(dplyr)
myUS %>%
    filter(!if_any(c(Gender, Education_Level, Industry), ~ .x == ""))

Or with if_all with !=

myUS %>%
    filter(if_all(c(Gender, Education_Level, Industry), ~ .x != ""))
Related