[R] Beginner problem - using mod function to print odd numbers
Bill Dunlap
w||||@mwdun|@p @end|ng |rom gm@||@com
Wed Jun 9 16:35:39 CEST 2021
Martin wrote
Use
num[num %% 2 == 1]
instead of much slower and ...@#^$
num[ifelse(num %% 2 == 1, TRUE, FALSE)]
Read the '[' as 'such that' when the subscript is logical
(=="Boolean"==TRUE/FALSE-values).
[The original post had a typo/thinko, num<-num+i instead of num<-num+1,
which was simply an error, not a matter of style. R's vectorization makes
it easy to avoid such errors.]
-Bill
On Wed, Jun 9, 2021 at 2:56 AM Martin Maechler <maechler using stat.math.ethz.ch>
wrote:
> >>>>> 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
>
> [............]
>
> ______________________________________________
> R-help using r-project.org mailing list -- To UNSUBSCRIBE and more, see
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide
> http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>
[[alternative HTML version deleted]]
More information about the R-help
mailing list