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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With