2 r tutorial programming

32
R Programming Sakthi Dasan Sekar

Upload: sakthi-dasans

Post on 14-Apr-2017

449 views

Category:

Data & Analytics


2 download

TRANSCRIPT

Page 1: 2 R Tutorial Programming

R ProgrammingSakthi Dasan Sekar

Page 2: 2 R Tutorial Programming

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

Page 3: 2 R Tutorial Programming

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

Page 4: 2 R Tutorial Programming

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

Page 5: 2 R Tutorial Programming

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

Page 6: 2 R Tutorial Programming

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

Page 7: 2 R Tutorial Programming

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 <- 20if(age > 18){

print("Major")} else {

print(“Minor”)}

http://shakthydoss.com 7

Page 8: 2 R Tutorial Programming

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

Page 9: 2 R Tutorial Programming

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

Page 10: 2 R Tutorial Programming

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

Page 11: 2 R Tutorial Programming

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

Page 12: 2 R Tutorial Programming

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:5for (val in num) {

if (val == 3){break

}print(val)

}

output 1, 2

http://shakthydoss.com 12

Page 13: 2 R Tutorial Programming

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

Page 14: 2 R Tutorial Programming

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

Page 15: 2 R Tutorial Programming

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

Page 16: 2 R Tutorial Programming

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

Page 17: 2 R Tutorial Programming

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

Page 18: 2 R Tutorial Programming

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

Page 19: 2 R Tutorial Programming

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

Page 20: 2 R Tutorial Programming

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

Page 21: 2 R Tutorial Programming

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

Page 22: 2 R Tutorial Programming

R Programming

Knowledge Check

http://shakthydoss.com 22

Page 23: 2 R Tutorial Programming

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

Page 24: 2 R Tutorial Programming

R Programming

4 __ 3 = 1. What operator should be used.

A. /

B. *

C. %/%

D. None of the above

Answer C

http://shakthydoss.com 24

Page 25: 2 R Tutorial Programming

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

Page 26: 2 R Tutorial Programming

R Programming

Can if statement be used without an else block.

A. Yes

B. No

Answer A

http://shakthydoss.com 26

Page 27: 2 R Tutorial Programming

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

Page 28: 2 R Tutorial Programming

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

Page 29: 2 R Tutorial Programming

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

Page 30: 2 R Tutorial Programming

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

Page 31: 2 R Tutorial Programming

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

Page 32: 2 R Tutorial Programming

R Programming

what will be the output of print.

num <- 1:5for (val in num) {

nextbreak

print(val)}

A. Error B. output 3,4,5C. Program runs but no output is producedD. None of the above

Answer C

http://shakthydoss.com 32