Remove rows in dataframe with factor ""

@Nick Sabbe provided a great answer, but it has one caveat:

Using -which(...) is a neat trick to (sometimes) speed up the subsetting operation when there are only a few elements to remove.

...But if there are no elements to remove, it fails!

So, if X$genes does not contain any empty strings, which will return an empty integer vector. Negating that is still an empty vector. And X[integer(0)] returns an empty data.frame!

toBeRemoved <- which(X$genes=="")
if (length(toBeRemoved>0)) { # MUST check for 0-length
    X<-X[-toBeRemoved,]
}

Or, if the speed gain isn't important, simply:

X<-X[X$genes!="",]

Or, as @nullglob pointed out,

subset(X, genes != "")

It's not completely obvious from your question what the empty values are, but you should be able to adopt the solution below (here I assume the 'empty' values are empty strings):

toBeRemoved<-which(X$genes=="")
X<-X[-toBeRemoved,]

Tags:

R

Dataframe