Vectorized Code

Ha Khanh Nguyen

Vectorized Code

  • The fastest R code will usually take advantage of three things:
    • logical tests
    • subsetting
    • element-wise execution
  • Code that uses these things usually has a certain quality: it is vectorized.
  • That means the code can take a vector of values as input and manipulate each value in the vector at the same time (parallel computing).

  • Example: Write an absolute value function in R that takes
    • Input: vec a vector of numbers
    • Ouput: a vector with all non-negative numbers
  • First method: for loop

  • Second method: vectorized code
  • Claim: abs_vectorized() is much faster than abs_loop().
    • Let test this claim!
##    user  system elapsed 
##   0.949   0.036   0.996
##    user  system elapsed 
##   0.236   0.055   0.294
  • How does our abs_vectorized() function compare to abs() built-in function?
##    user  system elapsed 
##   0.028   0.001   0.029

How to Write Vectorized Code

  • To create vectorized code:
    • Use vectorized functions (R built-in functions) to complete the sequential steps in your program.
    • Use logical subsetting to handle parallel cases. Try to manipulate every element in a case at once.
  • Example: abs_vectorized() function

##  [1] FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE FALSE  TRUE
## [1]  -2  -4  -6  -8 -10
## [1]  2  4  6  8 10
##  [1]   1  -2   3  -4   5  -6   7  -8   9 -10

Lookup Table

Another way to vectorize code is to use lookup table. Think lookup table as a dictionary.

##    user  system elapsed 
##   2.045   0.249   2.364

How to Write Fast for Loops in R

##    user  system elapsed 
##   0.430   0.151   0.611
##    user  system elapsed 
##   0.075   0.006   0.083

Vectorized Code in Practice

  • Remember Exercise 2 from Monday’s lecture?
  • From a given list of fruits, select only the ones that have 6 or fewer letters.
## [1] "apple"  "orange" "peach"  "plum"   "banana" "kiwi"   "papaya" "grapes"
  • How do we vectorize the above code?
    • First, is nchar() following element-wise execution?
##  [1]  5  9 10  6  5  4  8  6  4  6  6 10  9 10
##  [1]  TRUE FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
## [13] FALSE FALSE
## [1] "apple"  "orange" "peach"  "plum"   "banana" "kiwi"   "papaya" "grapes"

To-do

  • Submit Homework 2. Due at 11:59 PM on Compass.
  • Homework 3 has been published.

References