R Programming
- Overview of R
- Installing R on Windows
- Download and Install RStudio on Windows
- Setting Your Working Directory (Windows)
- Getting Help with R
- Installing R Packages
- Loading R Packages
- Take Input and Print in R
- R Objects and Attributes
- R Data Structures
- R – Operators
- Vectorization
- Dates and Times
- Data Summary
- Reading and Writing Data to and from R
- Control Structure
- Loop Functions
- Functions
- Data Frames and dplyr Package
- Generating Random Numbers
- Random Number Seed in R
- Random Sampling
- Data Visualization Using R
R – Operators
R language has so many built-in operators to perform different arithmetic and logical operations. There are mainly 4 types of operators in R.
- Arithmetic Operators
- Relational Operators
- Logical Operators
- Assignment Operators
- Mixed Operators
Arithmetic Operators in R:
Below table shows the arithmetic operators in R.
x <- 35
y<-10x+y
x-y
x*y
x/y
x%/%y
x%%y
x^y
Output:
> x+y
[1] 45
> x-y
[1] 25
> x*y
[1] 350
> x/y
[1] 3.5
> x%/%y
[1] 3
> x%%y
[1] 5
> x^y
[1] 2.758547e+15
Relational Operators in R:
Below table shows the relational operators in R.
x <- 35
y<-10x<y
x>y
x>=35
x<=35
y==10
x!=y
y!=10
Output:
> x<y
[1] FALSE
> x>y
[1] TRUE
> x>=35
[1] TRUE
> x<=35
[1] TRUE
> y==10
[1] TRUE
> x!=y
[1] TRUE
> y!=10
[1] FALSE
Logical Operators in R
Below table shows the logical operators in R. Operators & and | perform element-wise operation producing result having length of the longer operand.But && and || examines only the first element of the operands resulting into a single length logical vector.
See the below example properly, Zero is considered FALSE and non-zero numbers are taken as TRUE.
a <- c(TRUE,TRUE,FALSE,0,6,7)
b <- c(FALSE,TRUE,FALSE,TRUE,TRUE,TRUE)
a&b
a&&b
a|b
a||b
!a
!b
Output:
> a&b
[1] FALSE TRUE FALSE FALSE TRUE TRUE
> a&&b
[1] FALSE
> a|b
[1] TRUE TRUE FALSE TRUE TRUE TRUE
> a||b
[1] TRUE
> !a
[1] FALSE FALSE TRUE TRUE FALSE FALSE
> !b
[1] TRUE FALSE TRUE FALSE FALSE FALSE
Assignment Operators in R:
Below table shows the assignment operators in R. They are used to assign values to variables.
v1 <- 100
v2 <<-200
v3 = 300
v4<-c(1:10)1000 -> v5
200->> v6
20:30->>v7
v1
v2
v3
v4
v5
v6
v7
Output:
> v1
[1] 100
> v2
[1] 200
> v3
[1] 300
> v4
[1] 1 2 3 4 5 6 7 8 9 10
> v5
[1] 1000
> v6
[1] 200
> v7
[1] 20 21 22 23 24 25 26 27 28 29 30
Mixed Operators in R:
There are few other useful operators in R which are being used for specific purpose and not general mathematical or logical computation.
x<- 1:10
y<- 8
z<-20
x
y %in% x
z %in% xm<-matrix(1:9,3,3)
m%*%m
m*m
Output:
> x
[1] 1 2 3 4 5 6 7 8 9 10
> y %in% x
[1] TRUE
> z %in% x
[1] FALSE
>
> m<-matrix(1:9,3,3)
> m%*%m
[,1] [,2] [,3]
[1,] 30 66 102
[2,] 36 81 126
[3,] 42 96 150
> m*m
[,1] [,2] [,3]
[1,] 1 16 49
[2,] 4 25 64
[3,] 9 36 81