2. R Programming
Operators
R has many operators to carry out different mathematical and logical
operations.
Operators in R can be classified into the following categories.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
http://shakthydoss.com 2
3. R Programming
Arithmetic Operators
Arithmetic operators are used for mathematical operations like addition and
multiplication.
Arithmetic Operators in R
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
^ Exponent
%% Modulus
%/% Integer Division
http://shakthydoss.com 3
4. R Programming
Relational operators
Relational operators are used to compare between values.
Relational Operators in R
Operator Description
< Less than
> Greater than
<= Less than or equal to
>= Greater than or equal to
== Equal to
!= Not equal to
http://shakthydoss.com 4
5. R Programming
Logical Operators
Logical operators are used to carry out Boolean operations like AND, OR etc.
Logical Operators in R
Operator Description
! Logical NOT
& Element-wise logical AND
&& Logical AND
| Element-wise logical OR
|| Logical OR
http://shakthydoss.com 5
6. R Programming
Assignment operator
Assigment operators are used to assign values to variables.
Variables are assigned using <- (although = also works)
age <- 18 (left assignment )
18 -> age (right assignment)
http://shakthydoss.com 6
7. R Programming
if...else statement
Syntax
if (expression) {
statement
}
If the test expression is TRUE, the statement gets executed.
The else part is optional and is evaluated if test expression is FALSE.
age <- 20
if(age > 18){
print("Major")
} else {
print(“Minor”)
}
http://shakthydoss.com 7
8. R Programming
Nested if...else statement
Only one statement will get executed depending upon the test expressions.
if (expression1) {
statement1
} else if (expression2) {
statement2
} else if (expression3) {
statement3
} else {
statement4
}
http://shakthydoss.com 8
9. R Programming
ifelse() function
ifelse() function is nothing but a vector equivalent form of if..else.
ifelse(expression, yes, no)
expression– A logical expression, which may be a vector.
yes – What to return if expression is TRUE.
no – What to return if expression is FALSE.
a = c(1,2,3,4)
ifelse(a %% 2 == 0,"even","odd")
http://shakthydoss.com 9
10. R Programming
• For Loop
For loop in R executes code statements for a particular number of times.
for (val in sequence) {
statement
}
vec <- c(1,2,3,4,5)
for (val in vec) {
print(val)
}
http://shakthydoss.com 10
11. R Programming
While Loop
while (test_expression) {
statement
}
Here, test expression is evaluated and the body of the loop is entered if the
result is TRUE.
The statements inside the loop are executed and the flow returns to test
expression again.
This is repeated each time until test expression evaluates to FALSE.
http://shakthydoss.com 11
12. R Programming
break statement
A break statement is used inside a loop to stop the iterations and flow the control
outside of the loop.
num <- 1:5
for (val in num) {
if (val == 3){
break
}
print(val)
}
output 1, 2
http://shakthydoss.com 12
13. R Programming
next statement
A next statement is useful when you want to skip the current iteration of a loop alone.
num <- 1:5
for (val in num) {
if (val == 3){
next
}
print(val)
}
output 1,2,4,5
http://shakthydoss.com 13
14. R Programming
repeat loop
A repeat loop is used to iterate over a block of code multiple number of times.
There is no condition check in repeat loop to exit the loop.
You must specify exit condition inside the body of the loop.
Failing to do so will result into an infinite looping.
repeat {
statement
}
http://shakthydoss.com 14
15. R Programming
switch function
switch function is more like controlled branch of if else statements.
switch (expression, list)
switch(2, "apple", “ball" , "cat")
returns ball.
color = "green"
switch(color, "red"={print("apple")}, "yellow"={print("banana")},
"green"={print("avocado")})
returns avocado
http://shakthydoss.com 15
16. R Programming
scan() function
scan() function helps to read data from console or file.
reading data from console
x <- scan()
Reading data from file.
x <- scan("http://www.ats.ucla.edu/stat/data/scan.txt", what = list(age = 0,name = ""))
Reading a file using scan function may not be efficient way always.
we will see more handy functions to read files in upcoming chapters.
http://shakthydoss.com 16
17. R Programming
Running R Script
The source () function instructs R reads the text file and execute its contents.
source("myScript.R")
Optional parameter echo=TRUE will echo the script lines before they are
executed
source("myScript.R", echo=TRUE)
http://shakthydoss.com 17
18. R Programming
Running a Batch Script
R CMD BATCH command will help to run code in batch mode.
$ R CMD BATCH myscript.R outputfile
In case if you want the output sent to stdout or if you need to pass command-
line arguments to the script then Rscript command can be used.
$ Rscript myScript.R arg1 arg2
http://shakthydoss.com 18
19. R Programming
Commonly used R functions
append() Add elements to a vector.
c() Combine Values into a Vector or List
identical() Test if 2 objects are exactly equal.
length() Returns length of of R object.
ls() List objects in current environment.
range(x) Returns minimum and maximum of vector.
rep(x,n) Repeat the number x, n times
rev(x) Reversed version of its argument.
seq(x,y,n) Generate regular sequences from x to y, spaced by n
unique(x) Remove duplicate entries from vector
http://shakthydoss.com 19
20. R Programming
Commonly used R functions
tolower() Convert string to lower case letters
toupper() Convert string to upper case letters
grep() Used for Regular expressions
http://shakthydoss.com 20
21. R Programming
Commonly used R functions
summary(x) Returns Object Summaries
str(x) Compactly Display the Structure of an Arbitrary R Object
glimpse(x) Compactly Display the Structure of an Arbitrary R Object (dplyr package)
class(x) Return the class of an object.
mode(x) Get or set the type or storage mode of an object.
http://shakthydoss.com 21
23. R Programming
Which of following is valid equation.
A. TRUE %/% FALSE = TRUE
B. (TRUE | FALSE ) & (FALSE != TRUE) == TRUE
C. (TRUE | FALSE ) & (FALSE != TRUE) == FALSE
D. "A" && "a"
Answer B
http://shakthydoss.com 23
24. R Programming
4 __ 3 = 1. What operator should be used.
A. /
B. *
C. %/%
D. None of the above
Answer C
http://shakthydoss.com 24
25. R Programming
What will be output ?
age <- 18
18 -> age
print(age)
A. 18
B. Error
C. NA
D. Binary value of 18 will be stored in age.
Answer A
http://shakthydoss.com 25
26. R Programming
Can if statement be used without an else block.
A. Yes
B. No
Answer A
http://shakthydoss.com 26
27. R Programming
A break statement is used inside a loop to stop the iterations and flow
the control outside of the loop.
A. TRUE
B. FALSE
Answer A
http://shakthydoss.com 27
28. R Programming
A next statement is useful when you want to skip the current iteration
of a loop alone.
A. FALSE
B. TRUE
Answer B
http://shakthydoss.com 28
29. R Programming
Which function should be used to find the length of R object.
A. ls()
B. sizeOf()
C. length()
D. None of the above
Answer C
http://shakthydoss.com 29
30. R Programming
Display the Structure of an Arbitrary R Object
A. summary(x)
B. str(x)
C. ls(x)
D. None of above
Answer B
http://shakthydoss.com 30
31. R Programming
A repeat loop is used to iterate over a block of code multiple number of
times. There is no condition check in repeat loop to exit the loop.
A. TRUE
B. FALSE
Answer A
http://shakthydoss.com 31
32. R Programming
what will be the output of print.
num <- 1:5
for (val in num) {
next
break
print(val)
}
A. Error
B. output 3,4,5
C. Program runs but no output is produced
D. None of the above
Answer C
http://shakthydoss.com 32