Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid a loop here in R?

Tags:

loops

for-loop

r

In my R program I have a "for" loop of the following form:

for(i in 1:I)  
{  
res[i] <- a[i:I] %*% b[i:I]   
}

where res, a and b are vectors of length I.

Is there any straightforward way to avoid this loop and calculate res directly? If so, would that be more efficient?

Thanks in advance!

like image 334
Martin Avatar asked Apr 28 '14 14:04

Martin


People also ask

How do I stop a loop from running in R?

Just like with repeat and while loops, you can break out of a for loop completely by using the break statement.

How do you stop a loop in a condition in R?

Breaking the while loop in R To do this, we can use another break statement. Again, this functions the same way in a while loop that it does in a for loop; once the condition is met and break is executed, the loop ends.

Should you avoid for loops in R?

For that reason, it might make sense for you to avoid for-loops and to use functions such as lapply instead. This might speed up the R syntax and can save a lot of computational power! The next example explains how to use the lapply function in R.

Is apply faster than for loop R?

The apply functions (apply, sapply, lapply etc.) are marginally faster than a regular for loop, but still do their looping in R, rather than dropping down to the lower level of C code. For a beginner, it can also be difficult to understand why you would want to use one of these functions with their arcane syntax.


2 Answers

This is the "reverse cumsum" of a*b

rev(cumsum(rev(a) * rev(b)))
like image 87
ilir Avatar answered Sep 20 '22 10:09

ilir


So long as res is already of length I, the for loop isn't "incorrect" and the apply solutions will not really be any faster. However, using apply can be more succinct...(if potentially less readable)

Something like this:

res <- sapply(seq_along(a), function(i) a[i:I] %*% b[i:I])

should work as a one-liner.


Expanding on my first sentence. While using the inherent vectorization available in R is very handy and often the fastest way to go, it isn't always critical to avoid for loops. Underneath, the apply family determines the size of the output and pre-allocates it before "looping".

like image 44
Justin Avatar answered Sep 19 '22 10:09

Justin