Chapter 9 Logical Operations in R
9.1 Logical Operations in R
a<-2
b<-3
a==b # Checks if both variables are equal.If true, then returns TRUE else FALSE
## [1] FALSE
a>b # # Checks if Left hand side variable is greater than variable on the right hand side. If true then returns the value TRUE else FALSE
## [1] FALSE
a>=b # Checks if Left hand side variable is greater than or equal to variable on the right hand side. If true then returns the value TRUE else FALSE
## [1] FALSE
a<=b# Checks if Right hand side variable is greater than or equal to variable on the Left hand side. If true then returns the value TRUE else FALSE
## [1] TRUE
a!=b # Checks if Variable are equla or not
## [1] TRUE
Let’s Perform Logical Operations in R.
a<-c(1,2,3,4)
b<-c(5,6,7,8)
c<-c(1,2,3,4)
d<-c(1,2,5,6)
e<-c(1,2)
# When we perform Logical Operation in Vectors the operations is elementwise and cyclical.
a==b
## [1] FALSE FALSE FALSE FALSE
a==c
## [1] TRUE TRUE TRUE TRUE
b==d
## [1] FALSE FALSE FALSE FALSE
a>b
## [1] FALSE FALSE FALSE FALSE
b>a
## [1] TRUE TRUE TRUE TRUE
9.2 Comparing vectors of different length?
When applying an operation to two vectors that requires them to be the same length, R automatically recycles, or repeats, elements of the shorter one, until it is long enough to match the longer Vector.
# What happens when vectors of different lengths are compared?
a>e
## [1] FALSE FALSE TRUE TRUE
a>=e
## [1] TRUE TRUE TRUE TRUE
b>=e
## [1] TRUE TRUE TRUE TRUE
9.3 Logical Operands in R
ab<-a&b
ab
## [1] TRUE TRUE TRUE TRUE