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])
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.
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.
another approach
w = rowsum(z, v)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With