I've been encountering what I think is a bug. It's not a big deal, but I'm curious if anyone else has seen this. Unfortunately, my data is confidential, so I have to make up an example, and it's not going to be very helpful.
When subsetting my data, I occassionally get mysterious NA rows that aren't in my original data frame. Even the rownames are NA. EG:
example <- data.frame("var1"=c("A", "B", "A"), "var2"=c("X", "Y", "Z"))
example
var1 var2
1 A X
2 B Y
3 A Z
then I run:
example[example$var1=="A",]
var1 var2
1 A X
3 A Z
NA<NA> <NA>
Of course, the example above does not actually give you this mysterious NA row; I am adding it here to illustrate the problem I'm having with my data.
Maybe it has to do with the fact that I'm importing my original data set using Google's read.xlsx package and then executing wide to long reshape before subsetting.
Thanks
I see this was already answered by the OP, but since his comment is buried deep within the comment section, here's my attempt to fix this issue (at least with my data, which was behaving the same way).
First of all, some sample data:
Now for a simple filter:
The problem here is that the presence of
NA
s in the third column causes R to rewrite the whole row asNA
. Nonetheless, the data frame dimensions are maintained. Here's my fix, which requires knowledge of which column contains theNA
s:Probably this must be your result u are expecting...Try this try using which condition before condition to avoid NA's
Using dplyr:
Another cause may be that you get the condition wrong, such as checking if a factor column is equal to a value that is not among its levels. Troubled me for a while.
I get the same problem when using code similar to what you posted. Using the function subset()
the NA row instead gets excluded.
Wrap the condition in
which
:How it works:
It returns the row numbers where the condition matches (where the condition is
TRUE
) and subsets the data frame on those rows accordingly.Say that:
returns row numbers
1
,2
,3
,4
and5
.As such, writing:
is the same as writing:
Or an even simpler version is: