1. 1 / 8
R - vectorization()
A very brief intro
Zhenbo Li
linkedin.com/in/lizhenbo
github.com/Endle
lizhenbo@yahoo.com
This work is licensed under the Creative Commons Attribution 4.0 International License. To view a copy of this license, visit http://creativecommons.org/licenses/by/4.0/ or
send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA.
2. 2 / 8
●
Part I – Elementary
Arithmetic
C Python R
double a = 5.5;
double b = 2.0;
a = 5.5
b = 2.0
a <- 5.5
b <- 2.0
a + b a + b a + b
a - b a - b a - b
a * b a * b a * b
a / b a / b a / b
4. 4 / 8
Part II - Vectorization
/* C [0, n) */
#include <stdio.h>
double a[] = {1.1, 2.2, 3.3};
double b[] = {4.6, 5.6, 6.6};
double c[ sizeof(a) / sizeof(double) ];
int main()
{
unsigned i;
for (i = 0; i < 3; ++i) {
c[i] = a[i] + b[i];
printf("%fn", c[i]);
}
return 0;
}
# Python 3
a = [1.1, 2.2, 3.3]
b = [4.6, 5.6, 6.6]
# Naive way
c = list()
for i in range(len(a)):
c.append(a[i] + b[i])
# A bit smarter
c = [x[0] + x[1] for x in zip(a,b)]
5. 5 / 8
Part II - Vectorization
# R [1, n]
a <- c(1.1, 2.2, 3.3)
b <- c(4.6, 5.6, 6.6)
for (i in 1:length(a))
{
print(a[i] + b[i])
}
# R [1, n]
a <- c(1.1, 2.2, 3.3)
b <- c(4.6, 5.6, 6.6)
r <- a + b
print(r)
7. 7 / 8
Part III – Scalar & Vector
acceleration <- c(1.1, 2.2, 3.3) # m/s^2 in 3-dimensions
mass <- 5.6 # kg
force = mass * acceleration # Newton
print(force)
Scalar, aka 1-length vector, will be applied to all dimensions
8. 8 / 8
Summary
●
Vectorization is a basic R concept
●
You’re using vectorization before you
realize it
●
Further reading: Advanced R
– https://adv-r.hadley.nz/index.html
Cover image: Vector components and base change.svg by Jakob.scholbach
https://commons.wikimedia.org/wiki/File:Vector_components_and_base_change.svg
This file is licensed under the Creative Commons Attribution-Share Alike 3.0 Unported license.