Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 12

Introduction

R Programming - Lec 2
R - Statistical Programming Language
R is world’s most widely used statistics programming language. It's the # 1
choice of data scientists and supported by a vibrant and talented
community of contributors.
Looping
Example: for loop
Below is an example to count the number of even numbers in a vector.
x <- c(2,5,3,9,8,11,6)
count <- 0
for (val in x) {
if(val %% 2 == 0) count = count+1
}
print(count)

Output
[1] 3
Looping
Example of while Loop
i <- 1
while (i < 6) {
print(i)
i = i+1
}
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Taking input from user
my.name <- readline(prompt="Enter name: ")
my.age <- readline(prompt="Enter age: ")
# convert character into integer
my.age <- as.integer(my.age)
print(paste("Hi,", my.name, "next year you will be", my.age+1, "years old."))
Break statement
Example 1: break statement
x <- 1:5
for (val in x) {
if (val == 3){
break
}
print(val)
}
Output
[1] 1
[1] 2
Next statement
Example 2: Next statement
x <- 1:5
for (val in x) {
if (val == 3){
next
}
print(val)
}
Output
[1] 1
[1] 2
[1] 4
[1] 5
Repeat Loop
Example: repeat loop
x <- 1
repeat {
print(x)
x = x+1
if (x == 6){
break
}
}
Output
[1] 1
[1] 2
[1] 3
[1] 4
[1] 5
Functions in R
Syntax for Writing Functions in R
func_name <- function (argument) {
statement
}
• Here, we can see that the reserved word function is used to declare a function in
R.
• The statements within the curly braces form the body of the function. These
braces are optional if the body contains only a single expression.
• Finally, this function object is given a name by assigning it to a variable,
func_name.
Functions in R
Example of a Function
pow <- function(x, y) {
# function to print x raised to the power y
result <- x^y
print(paste(x,"raised to the power", y, "is", result))
}

Calling a function

>pow(8, 2)
[1] "8 raised to the power 2 is 64"
> pow(2, 8)
[1] "2 raised to the power 8 is 256”
Functions in R
Default Values for Arguments
We can assign default values to arguments in a function in R.

Here is the function with a default value for y.

pow <- function(x, y = 2) {


# function to print x raised to the power y
result <- x^y
print(paste(x,"raised to the power", y, "is", result))
}
The use of default value to an argument makes it optional when calling the function.
> pow(3)
[1] "3 raised to the power 2 is 9"
> pow(3,1)
[1] "3 raised to the power 1 is 3"
Functions in R
Example: return()
Let us look at an example which will return whether a given number is positive, negative or zero.
check <- function(x) {
if (x > 0) {
result <- "Positive"
}
else if (x < 0) {
result <- "Negative"
}
else {
result <- "Zero"
}
return(result)
}

Here, are some sample runs.


> check(1)
[1] "Positive"
> check(-10)
[1] "Negative"
> check(0)
[1] "Zero"

You might also like