R Programming - SPLessons
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

R Functions

R Functions

shape Description

Functions can be defined as a partitioned blocks of code in a program, which can be called any number of times during single execution of a program. The information is passed to the functions by using arguments. The following are the advantages of R programming.

Predefined Functions

shape Description

The following is the syntax for the function in R programming. [c]function_name <- function(arg_1, arg_2, ...) { Function body }[/c] In the above syntax, the function name will be stored as an object in R environment, function body determines exact functioning of the code. The following are the some important predefined functions.

seq()

The seq() is function is used to find the sequence of numbers between the range, the following is an example. [c] >print(seq(1,10)) 1 2 3 4 5 6 7 8 9 10 [/c]

mean()

The mean can be calculated as addition of total numbers and divide with total values, the following is an example. [c] > print(mean(25:82)) 53.5 [/c]

max()

The max() function is used to find the maximum value, the following is an example. [c] > print(max(25,82,222)) 222 [/c]

sum(x)

The sum() function is used to find the addition of given numbers, the following is an example. [c] > print(sum(25,82,222)) [1] 329 [/c]

User Defined Functions

shape Description

Here user can create own functions by using built in function, the following is an example to find the square of a given values. [c] # Create a function to print squares of numbers in sequence. new.function <- function(a) { for(i in 1:a) { b <- i^2 print(b) } } [/c] In the above example, new.function is the function name, while compile the code user need to pass an arguments so here 5 is the arguments passing as follows. [c]> new.function(5) [1] 1 [1] 4 [1] 9 [1] 16 [1] 25[/c] Here with out passing arguments also user can compile the code by giving logic as follows. [c]new.function <- function() { for(i in 1:5) { print(i^2) } } # Call the function without supplying an argument. new.function()[/c]

Summary

shape Key Points

  • The functions support lazy evaluation also.
  • Function declaration is also called as “function prototype”.
  • The primary advantage of function is that re usability.