0% found this document useful (0 votes)
20 views3 pages

Introduction To The R Language Introduction To The R Language

This document introduces vectorized operations in R. It explains that many R operations can be performed on entire vectors or matrices at once, making code more efficient and readable. Examples are provided of common vectorized arithmetic, logical comparison, and matrix operations like addition, multiplication, and division performed element-wise or using true matrix multiplication on entire vectors and matrices of data.

Uploaded by

der
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views3 pages

Introduction To The R Language Introduction To The R Language

This document introduces vectorized operations in R. It explains that many R operations can be performed on entire vectors or matrices at once, making code more efficient and readable. Examples are provided of common vectorized arithmetic, logical comparison, and matrix operations like addition, multiplication, and division performed element-wise or using true matrix multiplication on entire vectors and matrices of data.

Uploaded by

der
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Introduction to the R Language

Vectorized Operations

Roger Peng, Associate Professor


Johns Hopkins Bloomberg School of Public Health

Vectorized Operations
Many operations in R are vectorized making code more efficient, concise, and easier to read.
> x
> x
[1]
> x
[1]
> x
[1]
> y
[1]
> x
[1]
> x
[1]

<- 1:4; y <- 6:9


+ y
7 9 11 13
> 2
FALSE FALSE TRUE TRUE
>= 2
FALSE TRUE TRUE TRUE
== 8
FALSE FALSE TRUE FALSE
* y
6 14 24 36
/ y
0.1666667 0.2857143 0.3750000 0.4444444

2/3

Vectorized Matrix Operations


> x <- matrix(1:4, 2, 2); y <- matrix(rep(10, 4), 2, 2)
> x * y
## element-wise multiplication
[,1] [,2]
[1,]
10
30
[2,]
20
40
> x / y
[,1] [,2]
[1,] 0.1 0.3
[2,] 0.2 0.4
> x %*% y
## true matrix multiplication
[,1] [,2]
[1,]
40
40
[2,]
60
60

3/3

You might also like