Ron Gejman
Ron Gejman

Reputation: 6215

Data.frame becomes factor/vector after filtering/subsetting

I have a data.frame with one column, like so:

>d = data.frame(animal=c("horse","dog","cat"))

then I filter it by excluding all items also present in a vector. e.g.:

> res = d[!(d$animal %in% c("horse")),]
> res
[1] dog cat
Levels: cat dog horse
>class(res)
[1] "factor"

What is going on here?

Upvotes: 8

Views: 1449

Answers (1)

Prasad Chalasani
Prasad Chalasani

Reputation: 20282

Welcome to R. You've just been bitten by the drop annoyance: you need to explicitly tell R not to "drop to one-dimension":

res = d[!(d$animal %in% c("horse")), , drop = FALSE] 

Upvotes: 13

Related Questions