# [R] Beginner problem - using mod function to print odd numbers

Martin Maechler m@ech|er @end|ng |rom @t@t@m@th@ethz@ch
Wed Jun 9 11:55:40 CEST 2021

```>>>>> David Carlson    on Sun, 6 Jun 2021 15:21:34 -0400 writes:

> There is really no need for a loop:
> num <- 1:100
> num[ifelse(num %% 2 == 1, TRUE, FALSE)]

> [1]  1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43 45 47 49
> [26] 51 53 55 57 59 61 63 65 67 69 71 73 75 77 79 81 83 85 87 89 91 93 95 97 99

Well, and the above "works" but is really another proof of my
year-long claim that people use  ifelse(.)  *MUCH MUCH* too often,
and should really learn to use alternatives, in this case,
"R 101" (*long* before fooverse):

Use

num[num %% 2 == 1]

instead of much slower and ...@#^\$

num[ifelse(num %% 2 == 1, TRUE, FALSE)]

Martin Maechler
ETH Zurich

> On Sat, Jun 5, 2021 at 2:05 PM William Michels via R-help
> <r-help using r-project.org> wrote:
>>
>> > i <- 1L; span <- 1:100; result <- NA;
>> > for (i in span){
>> + ifelse(i %% 2 != 0, result[i] <- TRUE, result[i] <- FALSE)
>> + }
>> > span[result]
>> [1]  1  3  5  7  9 11 13 15 17 19 21 23 25 27 29 31 33 35 37 39 41 43

[............]

```