Define Functions in R

R

Learn how to define an own function to eliminate repetition from code and allows code reuse.

Rigoberto Chandomi Vazquez https://www.linkedin.com/in/rigoberto-chandomi-v%C3%A1zquez-79038495/
11-03-2021

Functions allow you to automate common tasks avoid copying and pasting. To create a new function you need to pick a name for the function, list the inputs or arguments and place the code you have developed in the body of the function.

Basic function template: name and body

#Functions

my_function <- function(arg1, arg2){
  
  #Do something
  
}

Function template with defaults arguments

my_function <- function(arg1, arg2, detail_arg = default1){
  
  #Do something
  
}

Example: function to estimate Z - Gas compressibility factor using Papay correlation

In this case two arguments are difined, pseudoreduced pressure and pseudoreduced temperature. The function is called z.papay and in its body is the equation. At the end we define the value that will be return as result.

\[ z = 1-\frac{3.53p_{pr}}{10^{0.9813T_{pr}}}+\frac{0.274p_{pr}^2}{10^{0.8157T_{pr}}}\]

z.papay <- function(Ppr, Tpr){
  
  #Ppr <- 3
  #Tpr <- 2
  z <- 1-(3.53*Ppr)/(10^(0.9813*Tpr))+(0.274*Ppr^2)/(10^(0.8157*Tpr))
  
  return(z)
  
}

Once the function is in the environment, we can use it to calculate Z value.

z.estimate <- z.papay(3, 2)

z.estimate
[1] 0.9421987

Bacause a vector is the simplest type of data structure in R, we can use a vector as a parameter in functions. A pseudoreduced pressure vector is defined to calculate z factor to constant pseudoreduced temperature

library(ggplot2)

Ppr <- seq(from = 0, to = 8, by = 0.2)
Tpr <- 1.6
Tpr2 <- 1.3

z_cal <- z.papay(Ppr, Tpr)
z_cal2 <- z.papay(Ppr, Tpr2)

z.value <- data.frame(Ppr = Ppr, z = z_cal, z2 = z_cal2)

plot_x <- ggplot(z.value) +
          geom_line(aes(x = Ppr, y = z), col = "red") + 
          geom_line(aes(x = Ppr, y = z2), col = "blue")

plot_x

Citation

For attribution, please cite this work as

Vazquez (2021, Nov. 3). Chato Solutions: Define Functions in R. Retrieved from https://www.chatosolutions.com/posts/2021-11-03-function1/

BibTeX citation

@misc{vazquez2021define,
  author = {Vazquez, Rigoberto Chandomi},
  title = {Chato Solutions: Define Functions in R},
  url = {https://www.chatosolutions.com/posts/2021-11-03-function1/},
  year = {2021}
}