1

I need to create a new object containing only the odd numbers from a variable of a dataset.

In this case I refer to the iris dataset and the variable Sepal.Length. The values of that variable are decimal with just one digit after the comma.

I take only the first 6 as an example:

vect_ex <- c(5.1, 4.9, 4.7, 4.6, 5.0, 5.4)

What I do not understand is that the modular division seems to work on a single number:

5.1 %% 0.2
# [1] 0.1

But not when I am using it in the indexing process:

vect_ex[vect_ex %% 0.2 == 0.1]
# numeric(0)

I know what I am doing is not the best way and neither the most efficient. Still, I am trying to learn R and I want to understand what is wrong with my code.

Moreover, the solution proposed for this exercise uses: iris[c(T,F),1] and I don't really understand how it works. Thanks.

benson23
  • 16,369
  • 9
  • 19
  • 38
Enri_Boss
  • 21
  • 3
  • 2
    This is to do with floating point equality. Check out the unexpected result of `5.1 %% 0.2 == 0.1` – Allan Cameron Feb 17 '22 at 11:32
  • 1
    Incidentally, the proposed solution gets the odd numbered _rows_ from the data set (i.e. the 1st, 3rd, 5th, etc.) . This is because the `c(T, F)` gets recycled, so the expression effectively becomes the same as `iris[c(T,F,T,F,T,F,T,F,T,F ...), 1]`. This selects every odd-numbered row from the first column of `iris` – Allan Cameron Feb 17 '22 at 11:38
  • Thank you for your answer. I guess the question of the exercise was poorly written since it seemed I had to find the odd values of the numbers in column Sepal.Length. – Enri_Boss Feb 17 '22 at 12:38

0 Answers0