Applied Computational Methods for Social Sciences
Lecture 4: Functions and Loops
Bogdan G. Popescu
John Cabot University
What You’ll Learn Today
- Writing your own functions
- Function elements, return values, and default arguments
- Repeating work with for loops
- Testing membership with the
%in% operator
- Practicing with classification and loop exercises
By the end, you’ll be able to package your code into reusable functions and automate repetitive tasks.
Functions
A function is a block of code which only runs when it is called.
You can pass data, known as arguments, into a function.
A function can return data as a result.
Functions
Functions
Functions
Functions Examples
Here is for example a function.
The function evaluates a statement and produces an output
This is what we had before:
x = -5
if (x > 0) {
print('x is positive!')
} else {
print('x is negative or zero!')
}
[1] "x is negative or zero!"
Functions Examples
This is how we write this as a function called is_this_no_positive
is_this_no_positive<-function(x)
Functions Examples
This is how we write this as a function called is_this_no_positive
is_this_no_positive<-function(x) {
if(x > 0)
Functions Examples
This is how we write this as a function called is_this_no_positive
is_this_no_positive<-function(x) {
if(x > 0) {
message <- 'x is positive!'
}
Functions Examples
This is how we write this as a function called is_this_no_positive
is_this_no_positive<-function(x) {
if(x > 0) {
message <- 'x is positive!'
} else
Functions Examples
This is how we write this as a function called is_this_no_positive
is_this_no_positive<-function(x) {
if (x > 0) {
message <- 'x is positive!'
} else {
message <- 'x is negative or zero!'
}
Functions Examples
This is how we write this as a function called is_this_no_positive
is_this_no_positive<-function(x) {
if (x > 0) {
message <- 'x is positive!'
} else {
message <- 'x is negative or zero!'
}
return(message)
}
Functions Examples
This is how we use this function:
is_this_no_positive<-function(x) {
if (x > 0) {
message <- 'x is positive!'
} else {
message <- 'x is negative or zero!'
}
return(message)
}
is_this_no_positive(3)
What is the output of this command?
Functions Examples
This is how we use this function:
is_this_no_positive<-function(x) {
if (x > 0) {
message <- 'x is positive!'
} else {
message <- 'x is negative or zero!'
}
return(message)
}
is_this_no_positive(3)
Functions Examples
What about now?
is_this_no_positive<-function(x) {
if (x > 0) {
message <- 'x is positive!'
} else {
message <- 'x is negative or zero!'
}
return(message)
}
is_this_no_positive(-3)
Functions Examples
What about now?
is_this_no_positive<-function(x) {
if (x > 0) {
message <- 'x is positive!'
} else {
message <- 'x is negative or zero!'
}
return(message)
}
is_this_no_positive(-3)
[1] "x is negative or zero!"
Functions Examples
Let us now create a third condition: x==0
is_this_no_positive<-function(x) {
if(x > 0) {
message <- 'x is positive!'
}
Functions Examples
Let us now create a third condition: x==0
is_this_no_positive<-function(x) {
if(x > 0) {
message <- 'x is positive!'
}
if(x==0){
message <- 'x is zero!'
}
Functions Examples
Let us now create a third condition: x==0
is_this_no_positive<-function(x) {
if(x > 0) {
return('x is positive!')
}
if(x==0){
message <- 'x is zero!'
} else {
message <-'x is negative or zero!'
}
return(message)
}
Functions Examples
Let us now create a third condition: x==0
is_this_no_positive<-function(x) {
if(x > 0) {
return('x is positive!')
}
if(x==0){
message <- 'x is zero!'
} else {
message <-'x is negative or zero!'
}
return(message)
}
is_this_no_positive(0)
Functions Examples
Here is another example of a function.
We create a function called add_five that has one parameter x.
The function calculates and returns the sum of x and 5.
add_five <- function(x) {
x_plus_five <- x + 5
return(x_plus_five)
}
Functions Examples
add_five <- function(x) {
x_plus_five <- x + 5
return(x_plus_five)
}
Here are the elements of the function:
- A function name (
add_five )
- The assignment operator (
<- )
- The
function operator ( function )
- Parameter(s), inside parentheses and separated by commas (
(x) )
Functions Examples
add_five <- function(x) {
x_plus_five <- x + 5
return(x_plus_five)
}
Here are the elements of the function:
- Code (
x_plus_five <- x + 5)
- Returned value (
return(x_plus_five))
Functions Examples
The function add_five, can be used to calculate the sum of various numbers and five
# Function definition
add_five <- function(x) {
x_plus_five <- x + 5
return(x_plus_five)
}
Here is what happens if we use 5 as a parameter
# Function call, with argument 5
add_five(5)
Functions Examples
Here is what happens if we use 77 as a parameter
# Function call, with argument 77
add_five(77)
Functions Examples
We can of course assign the result of a function to an object.
# Function call, with argument 77
x<-add_five(77)
x
Functions Examples
We can write the same function in a different way
# Original Function
add_five <- function(x) {
x_plus_five <- x + 5
return(x_plus_five)
}
# Version 2
add_five <- function(x) {
x + 5
}
# Version 3
add_five <- function(x) x + 5
Default Arguments
Default arguments can be specified as part of the function definition.
For example, the following definition add_five does not specify a default value for x
Thus, trying to call add_five without passing an argument for x gives an error
add_five <- function(x) x + 5
add_five()
## Error in add_five(): argument "x" is missing, with no default
Default Arguments
The following, an alternative definition, does specify the default value of 1 for x
The default value is then used when calling the function without specifying x:
add_five <- function(x = 1) x + 5
add_five()
Default Arguments
The following argument will also yield an error
add_five <- function(x) x + 5
add_five("five")
## Error in x + 5: non-numeric argument to binary operator
Exercises with Functions 1
Objective
Write an R script that classifies a given number into one of three categories using a function:
- Positive: If the number is greater than 0
- Negative: If the number is less than 0
- Zero: If the number is exactly 0
Let’s say the number is 3.
Exercises with Functions 1
Instructions
Use a function to classify the number into one of the categories. The output should look like below:
[1] "The number is Positive ."
Exercises with Functions 2
Objective
Write an R script that classifies a person into different age groups using a function, based on the following criteria:
- Child: 0 to 12 years old
- Teenager: 13 to 19 years old
- Adult: 20 to 59 years old
- Senior: 60 years old and above
Let’s say the age is 15.
Exercises with Functions 2
Instructions
Use if-else statements to classify the age into one of the age groups within a function.
[1] "You are a Teenager."
Exercises with Functions 3
Objective
Write an R script that classifies temperatures into different categories using a function based on the following criteria:
- Cold: Less than 50 degrees Fahrenheit
- Moderate: 50 to 75 degrees Fahrenheit
- Warm: 76 to 90 degrees Fahrenheit
- Hot: More than 90 degrees Fahrenheit
Exercises with Functions 3
Instructions
Use if-else statements within a function to classify the temperature into one of the categories.
[1] "The temperature is Moderate."
Loops
A loop is used to execute a given code section more than once.
A for loop is composed of:
- The variable name which we assign to the current vector element (
symbol)
- The vector we go over (sequence)
- A code which defines what to do with each element (expression)
Loops
This is the syntax in a for loop
for(item in sequence) {
expressions
}
Loops Example
This is an example of a for loop:
Loops Example
This is an example of a for loop:
Loops Example
This is an example of a for loop:
x <-c(1,2,3)
x
for (i in x)
Loops Example
This is an example of a for loop:
x <-c(1,2,3)
x
for (i in x) {
print(i)
}
Loops Example
This is an example of a for loop:
for (i in x) {
print(i)
}
Loops Example
Here is another example with strings:
x <-c("one", "two", "three")
x
Loops Example
Here is another example with strings:
x <-c("one", "two", "three")
x
for (i in x) {
print(i)
}
[1] "one"
[1] "two"
[1] "three"
Loops Example
Here is another example:
Loops Example
Here is another example:
x <-c(1,2,3)
for (i in x) {
print(i*2)
}
Loops Example
Here is another example:
x <-c(1,2,3)
for (i in x) {
print(i*2)
}
Exercises with Loops 1
- Create a vector of numbers from 1 to 10.
- Use a
for loop to iterate through the vector and print each element.
- Calculate the square of each element and store it in a new vector.
- Print the original vector and the vector containing the squares.
Exercises with Loops 1
The output should look like below
[1] "1, 1"
[1] "2, 4"
[1] "3, 9"
[1] "4, 16"
[1] "5, 25"
[1] "6, 36"
[1] "7, 49"
[1] "8, 64"
[1] "9, 81"
[1] "10, 100"
Exercises with Loops 2
- Create a vector of odd numbers from 1 to 15.
- Use a for loop to iterate through the vector and print each element.
- Calculate the square root of each element and store it in a new vector.
- Print the original vector and the vector containing the square root.
Exercises with Loops 2
The output should look like below.
[1] "1, 1"
[1] "3, 1.73205080756888"
[1] "5, 2.23606797749979"
[1] "7, 2.64575131106459"
[1] "9, 3"
[1] "11, 3.3166247903554"
[1] "13, 3.60555127546399"
[1] "15, 3.87298334620742"
Exercises with Loops 3
- Create a vector of numbers from 1 to 15.
- Calculate the square root of each odd element and store it in a new vector.
- Print the original vector and the odd vector containing the square roots.
Exercises with Loops 3
The output should look like below
[1] 1
[1] 2
[1] 1.732051
[1] 4
[1] 2.236068
[1] 6
[1] 2.645751
[1] 8
[1] 3
[1] 10
[1] 3.316625
[1] 12
[1] 3.605551
[1] 14
[1] 3.872983
The %in% operator
The %in% operator returns a logical vector indicating the presence of each element of x in y
For example:
The %in% operator
The %in% operator returns a logical vector indicating the presence of each element of x in y
For example:
x <-c(1,2,3)
y <-c(1,2,3,4)
The %in% operator
The %in% operator returns a logical vector indicating the presence of each element of x in y
For example:
x <-c(1,2,3)
y <-c(1,2,3,4)
x %in% y
The %in% operator
The %in% operator returns a logical vector indicating the presence of each element of x in y
For example:
x <-c(1,2,3)
y <-c(1,2,3,4)
x %in% y
Exercise with the %in% operator 1
- Create two vectors, one representing even numbers from 1 to 10, and another representing a set of numbers (some of which are even).
- Use the
%in% operator to identify and print the even numbers from the second vector that are also present in the first vector.
- Calculate the square of each identified even number and store it in a new vector.
Exercise with the %in% operator 1
# Create two vectors
even_numbers <- 2 * (1:5) # 2, 4, 6, 8, 10
mixed_numbers <- c(3, 6, 8, 9, 12)
The output should look like below
Exercise with the %in% operator 2
Finding common elements using %in% and a loop
# Create two vectors
vector1 <- c(1, 2, 3, 4, 5)
vector2 <- c(3, 5, 7, 9, 11)
The output should look like below
What Have We Learned?
- Wrote functions with parameters, return values, and default arguments
- Saw three equivalent ways to define the same function
- Automated repetition with for loops over numbers and strings
- Tested membership with the
%in% operator
- Practiced combining functions, conditionals, and loops in exercises
Next: applying these building blocks to real data.