How to Create Some Functions [func()] using R?

Creating some functions using R

Hello everyone, in this section, I want to share with you how to create some functions in the R language. In some cases, maybe we face a problem that is ineffective when finished using traditional calculations or manual processes. So, we need a function that may work effectively and efficiently in solving our problems.

In this post, we want to practice how to make some simple functions which may finish some cases. I will provide examples below based on my daily work experiences. Some of these examples may be new to you, but the important thing is that I hope you could catch the point of making functions.

In the certain stage of practice, we will use special package like dplyr. Like pandas in python, dplyr has some functions that we need for data manipulation.

Furthermore, we want to practice how to build a function using one or more parameters that we used to solve our problem. At the end of this post, we will try to solve some quadratic equations using the ABC formula with the function that we built earlier.

Okay, let us practice it sequentially using some codes below:


# create a function with a parameter
hasil <- function(x){
  y <- x^2
  return(y)
}
hasil(2)
## [1] 4
# create a function with 2 parameters
hasil <- function(x, y){
  z <- x - y
  return(z)
}
hasil(2, 5)
## [1] -3
# create a function with 3 parameters
hitung <- function(x, y, z){
  hasil <- sqrt(x^2 + y^2 + z^2)
  return(hasil)
}
hitung(2, 3, 4)
## [1] 5.385165
# create a function with a parameter and constant parameter
hasil <- function(x, y = 6){
  z <- x*y
  return(z)
}
hasil(0.6)
## [1] 3.6
# create a function to calculate integral
integral <- function(x){
  return(x^2)
}
integrate(integral, lower = 0, upper = 5)
## 41.66667 with absolute error < 4.6e-13
# create a function for generating certain function
fungsi_generator <- function(pangkat) {
  return(function(x) {
    return(x^pangkat)
  })
}
# generating function
fungsi_kuadrat <- fungsi_generator(2)
fungsi_kubik <- fungsi_generator(3)

# calculate the value using a generated function
fungsi_kuadrat(3)
## [1] 9
fungsi_kubik(3)
## [1] 27
# create 2 conditional functions using cat()
hasil <- function(x){
  if(x > 0){
    cat("Logic")
  }
  else{
    cat("Unlogic")
  }
}
hasil(0)
## Unlogic
# create 3 conditional functions using cat()
hasil <- function(x){
  if(x > 0){
    cat("Good")
  }
  else if(x == 0){
    cat("Moderate")
  }
  else{
    cat("Bad")
  }
}
hasil(1)
## Good
# create 3 conditional functions using if-else
hasil <- function(x){
    cat(ifelse(x > 0, "Good", ifelse(x == 0, "Moderate", "Bad")))
}
hasil(0)
## Moderate
# create 3 conditional functions with general conditions
hasil <- function(x){
  if(x > 0){
    return("Positive")
  }
  else if (x < 0){
    return("Negative")
  }
  else {
    return("Zero")
  }
}
hasil(-1)
## [1] "Negative"
# create a function with multiple choice operations
library(dplyr)
hasil <- function(x, y, op){
  hitung <- case_when(
    op == "plus" ~ as.character(x + y),
    op == "minus" ~ as.character(x - y),
    op == "multiply" ~ as.character(x * y),
    TRUE ~ "Operation not valid!"
  )
  return(hitung)
}

hasil(2, 3, "minus")
## [1] "-1"
# create a function to calculate the equation roots
# as we know, the quadratic equation is written as ax^2 + bx + c = 0
# to calculate its roots, we use the ABC formula
# x1,2 = (-b +/- sqrt(b^2 - 4ac)/2a)
akarpersamaan <- function(a, b, c){
  # calculate the discriminant (D)
  d <- b^2 - 4*a*c
  # declare x1 and x2
  x1 <- NULL
  x2 <- NULL
  # check the value of D
  if(d >= 0){
    # root of D
    akard <- sqrt(d)
    # calculate the roots of the quadratic equation
    x1 <- (-b + akard)/(2*a)
    x2 <- (-b - akard)/(2*a)
  }
  else{
    print("Discriminant < 0 or Imaginary roots")
  }
  hasil <- data.frame(x1 = x1, x2 = x2, discriminant = d)

  return(hasil)
}

# implement the function to the first equation 2x^2 + 3x - 1 = 0
akarpersamaan(2, 3, -1)
##          x1        x2 discriminant
## 1 0.2807764 -1.780776           17
# implement the function to the second equation x^2 + x + 1 = 0
akarpersamaan(1, 1, 1)
## [1] "Discriminant < 0 or Imaginary roots"
## Error in data.frame(x1 = x1, x2 = x2, discriminant = d): arguments imply differing number of rows: 0, 1

Happy learning and practicing!

Tidak ada komentar:

Diberdayakan oleh Blogger.