Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data.frame becomes factor/vector after filtering/subsetting

Tags:

dataframe

r

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?

like image 547
Ron Gejman Avatar asked Feb 02 '11 18:02

Ron Gejman


1 Answers

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] 
like image 84
Prasad Chalasani Avatar answered Oct 22 '22 00:10

Prasad Chalasani