SlideShare a Scribd company logo
1 of 8
Download to read offline
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 / 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
3 / 8
Summary
●
Elementary arithmetic
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 / 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)
6 / 8
Part II - Vectorization
library(datasets)
data(iris)
library(dplyr)
virginica <- iris %>% filter(Species == "virginica") %>% head(1)
virginica <- virginica[1:4] %>% unlist
setosa <- iris %>% filter(Species == "setosa") %>% head(1)
setosa <- setosa[1:4] %>% unlist
norm_vec <- function(x) sqrt(sum(x^2))
cosine_similarity <- sum(virginica * setosa) /
(norm_vec(virginica) * norm_vec(setosa))
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
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.

More Related Content

What's hot

Bayesian learning
Bayesian learning Bayesian learning
Bayesian learning EngReads
 
Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stackHaqnawaz Ch
 
Three Functional Programming Technologies for Big Data
Three Functional Programming Technologies for Big DataThree Functional Programming Technologies for Big Data
Three Functional Programming Technologies for Big DataDynamical Software, Inc.
 
More Multiplication Properties Exponents
More Multiplication Properties ExponentsMore Multiplication Properties Exponents
More Multiplication Properties ExponentsBitsy Griffin
 
Advanced python concepts
Advanced python conceptsAdvanced python concepts
Advanced python conceptsManusha Dilan
 
Python for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo CruzPython for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo Cruzrpmcruz
 
Monad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional ProgrammingMonad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional ProgrammingNamuk Park
 
computer notes - Data Structures - 26
computer notes - Data Structures - 26computer notes - Data Structures - 26
computer notes - Data Structures - 26ecomputernotes
 
構文や語彙意味論の分析成果をプログラムとして具現化する言語 パターンマッチAPIの可能性
構文や語彙意味論の分析成果をプログラムとして具現化する言語パターンマッチAPIの可能性構文や語彙意味論の分析成果をプログラムとして具現化する言語パターンマッチAPIの可能性
構文や語彙意味論の分析成果をプログラムとして具現化する言語 パターンマッチAPIの可能性kktctk
 
PyParis - weather and climate data
PyParis - weather and climate dataPyParis - weather and climate data
PyParis - weather and climate dataMargriet Groenendijk
 

What's hot (12)

Bayesian learning
Bayesian learning Bayesian learning
Bayesian learning
 
Illustrator_Sample
Illustrator_SampleIllustrator_Sample
Illustrator_Sample
 
Conversion from infix to prefix using stack
Conversion from infix to prefix using stackConversion from infix to prefix using stack
Conversion from infix to prefix using stack
 
Three Functional Programming Technologies for Big Data
Three Functional Programming Technologies for Big DataThree Functional Programming Technologies for Big Data
Three Functional Programming Technologies for Big Data
 
Practical no 4
Practical no 4Practical no 4
Practical no 4
 
More Multiplication Properties Exponents
More Multiplication Properties ExponentsMore Multiplication Properties Exponents
More Multiplication Properties Exponents
 
Advanced python concepts
Advanced python conceptsAdvanced python concepts
Advanced python concepts
 
Python for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo CruzPython for Scientific Computing -- Ricardo Cruz
Python for Scientific Computing -- Ricardo Cruz
 
Monad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional ProgrammingMonad and Algebraic Design in Functional Programming
Monad and Algebraic Design in Functional Programming
 
computer notes - Data Structures - 26
computer notes - Data Structures - 26computer notes - Data Structures - 26
computer notes - Data Structures - 26
 
構文や語彙意味論の分析成果をプログラムとして具現化する言語 パターンマッチAPIの可能性
構文や語彙意味論の分析成果をプログラムとして具現化する言語パターンマッチAPIの可能性構文や語彙意味論の分析成果をプログラムとして具現化する言語パターンマッチAPIの可能性
構文や語彙意味論の分析成果をプログラムとして具現化する言語 パターンマッチAPIの可能性
 
PyParis - weather and climate data
PyParis - weather and climate dataPyParis - weather and climate data
PyParis - weather and climate data
 

Similar to R vectorization

Lab Manual IV (1).pdf on C++ Programming practice
Lab Manual IV (1).pdf on C++ Programming practiceLab Manual IV (1).pdf on C++ Programming practice
Lab Manual IV (1).pdf on C++ Programming practiceranaibrahim453
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonCarlos V.
 
Getting started with R when analysing GitHub commits
Getting started with R when analysing GitHub commitsGetting started with R when analysing GitHub commits
Getting started with R when analysing GitHub commitsBarbara Fusinska
 
PRE: Datamining 2nd R
PRE: Datamining 2nd RPRE: Datamining 2nd R
PRE: Datamining 2nd Rsesejun
 
Datamining R 1st
Datamining R 1stDatamining R 1st
Datamining R 1stsesejun
 
Datamining r 1st
Datamining r 1stDatamining r 1st
Datamining r 1stsesejun
 
Shallow copy and deep copy
Shallow copy and deep copyShallow copy and deep copy
Shallow copy and deep copyJanu Jahnavi
 
Shallow copy and deep copy
Shallow copy and deep copyShallow copy and deep copy
Shallow copy and deep copyJanu Jahnavi
 
Some stuff about C++ and development
Some stuff about C++ and developmentSome stuff about C++ and development
Some stuff about C++ and developmentJon Jagger
 
Breaking a Stick to form a Pentagon with Positive Integers using Programming ...
Breaking a Stick to form a Pentagon with Positive Integers using Programming ...Breaking a Stick to form a Pentagon with Positive Integers using Programming ...
Breaking a Stick to form a Pentagon with Positive Integers using Programming ...IRJET Journal
 
Array matrix example programs - C language
Array matrix example programs - C languageArray matrix example programs - C language
Array matrix example programs - C languageSk_Group
 
รายงานการเขียนคำสั่งควบคุมแบบวนซ้ำ กลุ่ม 4 ม. 6 ห้อง2
รายงานการเขียนคำสั่งควบคุมแบบวนซ้ำ กลุ่ม 4 ม. 6 ห้อง2รายงานการเขียนคำสั่งควบคุมแบบวนซ้ำ กลุ่ม 4 ม. 6 ห้อง2
รายงานการเขียนคำสั่งควบคุมแบบวนซ้ำ กลุ่ม 4 ม. 6 ห้อง2Pookie Pook
 
R Matrix Math Quick Reference
R Matrix Math Quick ReferenceR Matrix Math Quick Reference
R Matrix Math Quick ReferenceMark Niemann-Ross
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Pythonpugpe
 
Ramco Sample Paper 2003
Ramco  Sample  Paper 2003Ramco  Sample  Paper 2003
Ramco Sample Paper 2003ncct
 

Similar to R vectorization (20)

Lab Manual IV (1).pdf on C++ Programming practice
Lab Manual IV (1).pdf on C++ Programming practiceLab Manual IV (1).pdf on C++ Programming practice
Lab Manual IV (1).pdf on C++ Programming practice
 
LalitBDA2015V3
LalitBDA2015V3LalitBDA2015V3
LalitBDA2015V3
 
Functional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with PythonFunctional Programming inside OOP? It’s possible with Python
Functional Programming inside OOP? It’s possible with Python
 
Getting started with R when analysing GitHub commits
Getting started with R when analysing GitHub commitsGetting started with R when analysing GitHub commits
Getting started with R when analysing GitHub commits
 
Python Puzzlers
Python PuzzlersPython Puzzlers
Python Puzzlers
 
Java Bytecodes by Example
Java Bytecodes by ExampleJava Bytecodes by Example
Java Bytecodes by Example
 
PRE: Datamining 2nd R
PRE: Datamining 2nd RPRE: Datamining 2nd R
PRE: Datamining 2nd R
 
Datamining R 1st
Datamining R 1stDatamining R 1st
Datamining R 1st
 
Datamining r 1st
Datamining r 1stDatamining r 1st
Datamining r 1st
 
Shallow copy and deep copy
Shallow copy and deep copyShallow copy and deep copy
Shallow copy and deep copy
 
Shallow copy and deep copy
Shallow copy and deep copyShallow copy and deep copy
Shallow copy and deep copy
 
GCC
GCCGCC
GCC
 
Some stuff about C++ and development
Some stuff about C++ and developmentSome stuff about C++ and development
Some stuff about C++ and development
 
Breaking a Stick to form a Pentagon with Positive Integers using Programming ...
Breaking a Stick to form a Pentagon with Positive Integers using Programming ...Breaking a Stick to form a Pentagon with Positive Integers using Programming ...
Breaking a Stick to form a Pentagon with Positive Integers using Programming ...
 
Keras & R
Keras & RKeras & R
Keras & R
 
Array matrix example programs - C language
Array matrix example programs - C languageArray matrix example programs - C language
Array matrix example programs - C language
 
รายงานการเขียนคำสั่งควบคุมแบบวนซ้ำ กลุ่ม 4 ม. 6 ห้อง2
รายงานการเขียนคำสั่งควบคุมแบบวนซ้ำ กลุ่ม 4 ม. 6 ห้อง2รายงานการเขียนคำสั่งควบคุมแบบวนซ้ำ กลุ่ม 4 ม. 6 ห้อง2
รายงานการเขียนคำสั่งควบคุมแบบวนซ้ำ กลุ่ม 4 ม. 6 ห้อง2
 
R Matrix Math Quick Reference
R Matrix Math Quick ReferenceR Matrix Math Quick Reference
R Matrix Math Quick Reference
 
Palestra sobre Collections com Python
Palestra sobre Collections com PythonPalestra sobre Collections com Python
Palestra sobre Collections com Python
 
Ramco Sample Paper 2003
Ramco  Sample  Paper 2003Ramco  Sample  Paper 2003
Ramco Sample Paper 2003
 

Recently uploaded

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝soniya singh
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsMehedi Hasan Shohan
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxTier1 app
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)OPEN KNOWLEDGE GmbH
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 

Recently uploaded (20)

Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
Call Girls in Naraina Delhi 💯Call Us 🔝8264348440🔝
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
XpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software SolutionsXpertSolvers: Your Partner in Building Innovative Software Solutions
XpertSolvers: Your Partner in Building Innovative Software Solutions
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptxKnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
KnowAPIs-UnknownPerf-jaxMainz-2024 (1).pptx
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)Der Spagat zwischen BIAS und FAIRNESS (2024)
Der Spagat zwischen BIAS und FAIRNESS (2024)
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 

R vectorization

  • 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)
  • 6. 6 / 8 Part II - Vectorization library(datasets) data(iris) library(dplyr) virginica <- iris %>% filter(Species == "virginica") %>% head(1) virginica <- virginica[1:4] %>% unlist setosa <- iris %>% filter(Species == "setosa") %>% head(1) setosa <- setosa[1:4] %>% unlist norm_vec <- function(x) sqrt(sum(x^2)) cosine_similarity <- sum(virginica * setosa) / (norm_vec(virginica) * norm_vec(setosa))
  • 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.