[R] Multiple counters in a single for loop
Bert Gunter
bgunter@4567 @end|ng |rom gm@||@com
Fri Aug 24 17:28:23 CEST 2018
Sort of, but you typically wouldn't need to in R because of vectorization,
which buries the iteration in the underlying C code. Here's an example that
may clarify what I mean:
x <- cbind(1:5,6:10)
x ## a 2 column matrix
## get squares of all elements of x
## method 1
m1 <-x^2
##method 2: square the column vectors
m2 <- x
for (i in 1:2)m2[,i] <- m2[,i]^2
identical(m1,m2)
## of course, one could do this by row vectors, too
## method 3: loop through each element
m3 <- x
ix <- as.matrix(expand.grid(1:5,1:2))
ix
m3[ix]^2 ## matrix indexing of an array. This produces a vector,though.
Note also that there is an "iterators" package in R which implements
python-like iterators.I don't know how efficient it is, however.
My overall advice would be that you should try to program in R's native
paradigms, which emphasize whole object manipulation through vectorization,
rather than trying to use Python's, especially if efficiency is a
consideration. Feel free to ignore of course.
Cheers,
Bert
Bert Gunter
"The trouble with having an open mind is that people keep coming along and
sticking things into it."
-- Opus (aka Berkeley Breathed in his "Bloom County" comic strip )
On Fri, Aug 24, 2018 at 6:44 AM Deepa <deepamahm.iisc using gmail.com> wrote:
> Hello,
>
> Is there an option to include multiple counters in a single for loop in R?
>
> For instance, in python there is
>
> for i,j in zip(x,range(0,len(x))):
>
>
> Any suggestions?
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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