Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vectorizing a loop in R

Tags:

loops

r

There must be a simple way to vectorize the following loop in R, but I can't see it.

w <- numeric(10)
z <- rnorm(20)
v <- c(sample(1:10,10),sample(1:10,10)) #Random ordering of c(1:10,1:10)
for(i in 1:10)
    w[i] <- sum(z[v==i])
like image 378
Rob Hyndman Avatar asked Nov 13 '10 11:11

Rob Hyndman


People also ask

What does it mean to vectorize a loop?

Loop vectorization transforms procedural loops by assigning a processing unit to each pair of operands. Programs spend most of their time within such loops. Therefore, vectorization can significantly accelerate them, especially over large data sets.

What does it mean to vectorize in R?

Most of R's functions are vectorized, meaning that the function will operate on all elements of a vector without needing to loop through and act on each element one at a time. This makes writing code more concise, easy to read, and less error prone.


1 Answers

another approach

w = rowsum(z, v)
like image 163
Ramnath Avatar answered Sep 23 '22 18:09

Ramnath