-5

What's the idiomatic way in R to loop over 2 vectors like this in Python

for i,j in zip(Is, Js)

The obvious way in R is to go along the index

for (idx in seq_along(Is)) {
    i = Is[idx]
    j = Js[idx]

}

Just wonder if there is a less cumbersome way?

Edit:

I'm using for loop for parameter scan and then plotting. A preferred way to avoid for loop will be also helpful. So for example

results = data.table()
for (threshold in c(2,3,4,5)) {
    largeRtn = rtn[abs(rtn)>threshold*volatility]
    results = rbind(results, someAnalysis(largeRtn) )
    qplot(largeRtn, ...)
}
jf328
  • 6,841
  • 10
  • 58
  • 82
  • 6
    Can you elaborate on what you're trying to achieve? Generally, for-loops in R are not the way to go. You could consider providing a [reproducible example](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example). – Heroka Oct 20 '15 at 09:32
  • avoid it when you can - most functions take vectors as input, there arent nice iterators like in python. – Rorschach Oct 20 '15 at 09:37
  • @Heroka, I added one example although still not a "working example". – jf328 Oct 20 '15 at 10:53
  • Would you be able to answer this question given the data you've given? – Heroka Oct 20 '15 at 10:56
  • @Heroka, sorry, not sure what you mean – jf328 Oct 20 '15 at 11:00
  • Your question is incomplete and you show very little effort in either making it clearer/reproducible or commenting why the given solutions are not what you need. – Heroka Oct 20 '15 at 11:04

2 Answers2

2

Something like this is typically R-like:

func = function(a, b) {
    return(a*b)
}
a = c(2,3,1,7,8)
b = c(4,6,7,0,1)
mapply(func, a = a, b = b)
[1]  8 18  7  0  8

Of course in this case, one can easily do this vectorized:

a * b
[1]  8 18  7  0  8

But in more complex cases, vectorization might not be an option, then you can use the first approach.

Maybe this tutorial I wrote can help you out.

Paul Hiemstra
  • 59,984
  • 12
  • 142
  • 149
2

I'm not sure what your python code does, but maybe the foreach and iterators packages are an option:

library(foreach)
library(iterators)

zip <- function(...) iter(obj = expand.grid(...), by = "row")
foreach(d = zip(i = 1:3, j = 5:10), .combine = c) %do% {d[,"i"] * d[,"j"]}
#[1]  5 10 15  6 12 18  7 14 21  8 16 24  9 18 27 10 20 30

Of course, you should avoid loops if possible.

Roland
  • 127,288
  • 10
  • 191
  • 288