Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why subset returns only odd-numbered rows?

Tags:

r

subset

I tried to use the following code to subset the iris data

datanew = subset(iris, Species == c("setosa", "virginica"), select = -Species)

but the result I am getting is only the 1, 3, 5, 7...rows. Why did I end up getting odd rows?

like image 462
user2350622 Avatar asked Jul 30 '26 18:07

user2350622


1 Answers

Short answer: because of vector recycling, http://cran.r-project.org/doc/manuals/R-intro.html#Vector-arithmetic.

Long answer: when you are doing a comparison of the form x == y, if vectors x and y don't have the same length, the short one is recycled to match the length of the long one.

For example,

> x <- c(1, 1, 1, 2, 2, 2)
> y <- c(1, 2)
> x == y
[1]  TRUE FALSE  TRUE  TRUE FALSE  TRUE

You are essentially getting a result of comparison c(1, 1, 1, 2, 2, 2) == c(1, 2, 1, 2, 1, 2) - notice the second, shorter, vector is recycled.

subset uses vector comparison internally, and so the recycling rule applies there as well.

To get what you want, you have to replace == with %in%, as @Vincent has pointed out in another thread.

like image 154
Victor K. Avatar answered Aug 01 '26 07:08

Victor K.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!