Function in R Programming Language

Rumman Ansari   Software Engineer   2023-03-24   5848 Share
☰ Table of Contents

Table of Content:


Functions are defined using the function() directive and are stored as R objects just like anything else. In particular, they are R objects of class function.

Here’s a simple function that takes no arguments and does nothing.



 f <- function() {
     ## This is an empty function
     }
	 
 

Class of a Functions


> ## Functions have their own class
> class(f)
	 
 

Output

	[1] "function"

Execute the above Functions


> ## Execute this function
> f()
	 
 

Output

	NULL

Not very interesting, but it’s a start. The next thing we can do is create a function that actually has a non-trivial function body.


> f <- function() {
 cat("Hello, world!\n")
 }
> f()

 

Output

	Hello, world!

The last aspect of a basic function is the function arguments. These are the options that you can specify to the user that the user may explicity set. For this basic function, we can add an argument that determines how many times “Hello, world!” is printed to the console.


> f <- function(num) {
     for(i in seq_len(num)) {
         cat("Hello, world!\n")
       }
 }
> f(3)
 

Output

Hello, world!
Hello, world!
Hello, world!

Obviously, we could have just cut-and-pasted the cat("Hello, world!\n") code three times to achieve the same effect, but then we wouldn’t be programming, would we? Also, it would be un- neighborly of you to give your code to someone else and force them to cut-and-paste the code however many times the need to see “Hello, world!”.

In general, if you find yourself doing a lot of cutting and pasting, that’s usually a good sign that you might need to write a function.

Finally, the function above doesn’t return anything. It just prints “Hello, world!” to the console num number of times and then exits. But often it is useful if a function returns something that perhaps can be fed into another section of code.

This next function returns the total number of characters printed to the console.


> f <- function(num) {
 hello <- "Hello, world!\n"
    for(i in seq_len(num)) {
     cat(hello)
     }
  chars <- nchar(hello) * num
  chars
  }
 

Output

> meaningoflife <- f(3)
Hello, world!
Hello, world!
Hello, world!
> print(meaningoflife)
[1] 42