Introduction to Functions

In R, a function is a block of code that performs a specific task. You can define your own functions in R.

# A simple function to add two numbers
add_numbers <- function(x, y) {
  return(x + y)
}

# Call the function
add_numbers(5, 10)
## [1] 15

Exercises

  1. Write a function named square_number that takes a number as input and returns its square.
# Your code here
square_number <- function(x){
  return(x^2)
}
square_number(3)
## [1] 9
  1. Write a function named get_greeting that takes a name as input and returns a greeting message (e.g., “Hello, Charlie!”).
# Your code here
get_greeting <- function(name){
  return(paste("Hello",name,"!"))
}
get_greeting("Alif")
## [1] "Hello Alif !"
  1. Write a function named calculate_mean that takes a numeric vector as input and returns its mean.
# Your code here
calculate_mean <- function(numbers){
  return(mean(numbers))
}
calculate_mean(c(1,2,3,4,5))
## [1] 3
  1. Write a function that will return the sum of 2 integers.
# Your code here
sum_integers <- function(int1, int2){
  return(int1+int2)
}
sum_integers(1,2)
## [1] 3
  1. Write a function that will return TRUE if a given integer is inside a vector.
# Your code here
is_in_vector <- function(int, vec){
  return(int %in% vec)
}
is_in_vector(2, c(1,2,3))
## [1] TRUE
is_in_vector(2, c(1,4,3))
## [1] FALSE
  1. Write a function that, given a data frame, will print the name of each column and the class of data it contains (e.g., “Variable1 is Numeric”).
# Your code here
my_df <- data.frame(
  ID = 1:3,
  Name = c("A", "B", "C"),
  Value = c(10.5, 20.1, 30.0)
)

name_and_class <- function(df){
  for (col_name in names(df)) {
    cat(col_name,"is",class(df[[col_name]]),"\n")
  }
}

name_and_class(my_df)
## ID is integer 
## Name is character 
## Value is numeric
  1. Create a function that, given a vector and an integer, will return how many times the integer appears inside the vector.
# Your code here
count_occurrences <- function(vector, integer) {
  return(sum(vector == integer))
}
count_occurrences(c(1, 2, 2, 3, 2, 4), 2)
## [1] 3
print(c(1, 2, 2, 3, 2, 4) == 2)
## [1] FALSE  TRUE  TRUE FALSE  TRUE FALSE
  1. Create a function that, given a numeric vector, will print the mean and the standard deviation. It will optionally also print the median if the vector has an odd number of elements.
# Your code here
analyze_vector <- function(vector) {
  cat("Mean:", mean(vector), "\n")
  cat("Standard Deviation:", sd(vector), "\n")
  if (length(vector) %% 2 != 0) {
    cat("Median:", median(vector), "\n")
  }
}
analyze_vector(c(1, 2, 3, 4, 5))
## Mean: 3 
## Standard Deviation: 1.581139 
## Median: 3
analyze_vector(c(1, 2, 3, 4, 5, 6))
## Mean: 3.5 
## Standard Deviation: 1.870829
  1. Create a function that, given an integer, will calculate how many divisors it has (other than 1 and itself) and print the divisors.
# Your code here
find_divisors <- function(n) {
  divisors <- c()
  if (n > 3) {
    for (i in 2:(n - 1)) {
      if (n %% i == 0) {
        divisors <- c(divisors, i)
      }
    }
  }
  cat("Divisors of", n, ":", divisors, "\n")
  return(length(divisors))
}
find_divisors(12)
## Divisors of 12 : 2 3 4 6
## [1] 4
find_divisors(7)
## Divisors of 7 :
## [1] 0
  1. Create a function that, given a data frame and a value (number or character), will return the data frame with all occurrences of that value changed to NA.
# Your code here
replace_with_na <- function(df, value) {
  df[df == value] <- NA
  return(df)
}
my_df_2 <- data.frame(
  A = c(1, 2, 3),
  B = c("x", "y", "x")
)
print(my_df_2)
##   A B
## 1 1 x
## 2 2 y
## 3 3 x
replace_with_na(my_df_2, "x")
##   A    B
## 1 1 <NA>
## 2 2    y
## 3 3 <NA>
replace_with_na(my_df_2, 2)
##    A B
## 1  1 x
## 2 NA y
## 3  3 x

Solutions

Click here for the solutions