Back
Close

Computing with Data

elgeish
104.6K views

Vectorization

It is best to avoid loops when programming in R. There are two reasons for this: simplifying code and computational speed-up. Many mathematical computations on lists, vectors, or arrays may be performed without loops using component-wise arithmetic. The code below demonstrates the computational speedup resulting from replacing a loop with vectorized code:

a = 1:10
c = 0 # compute sum of squares using a for-loop
for (e in a) c = c + e^2
c
sum(a ^ 2) # same operation using vector arithmetic
a = 1:1000000
c = 0
# time comparison with a million elements
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
Create your playground on Tech.io
This playground was created on Tech.io, our hands-on, knowledge-sharing platform for developers.
Go to tech.io
codingame x discord
Join the CodinGame community on Discord to chat about puzzle contributions, challenges, streams, blog articles - all that good stuff!
JOIN US ON DISCORD
Online Participants