Functions in R, Math
Functions in R, Math
• A set of statements which are organized together to perform a specific task is known as a
function.
• R provides a series of in-built functions, and it allows the user to create their own
functions.
• Functions are used to perform tasks in the modular approach.
• Functions are used to avoid repeating the same task and to reduce complexity.
• To understand and maintain our code, we logically break it into smaller parts using the
function.
A function should be
1.func_name <- function(arg_1, arg_2, ...) {
2. Function body
3.}
Components of Functions
• Similar to the other languages, R also has two types of function, i.e. Built-in
Function and User-defined Function.
• In R, there are lots of built-in functions which we can directly call in the program without
defining them. R also allows us to create our own functions.
•
Built-in function
• The functions which are already created or defined in the programming framework are
known as built-in functions.
• User doesn't need to create these types of functions, and these functions are built into an
application. End-users can access these functions by simply calling it.
• R have different types of built-in functions such as seq(), mean(), max(), and sum(x) etc.
# Creating sequence of numbers from 32 to 46.
print(seq(32,46))
# Finding the mean of numbers from 22 to 80.
print(mean(22:80))
# Finding the sum of numbers from 41 to 70.
print(sum(41:70))
User-defined function
• R allows us to create our own function in our program. A user defines a user-define
function to fulfill the requirement of user. Once these functions are created, we can use
these functions like in-built function.
new.function()
R has a rich set of functions that can be used to perform almost every task for the
user.
Mathematical Functions
Summary Functions
String Functions
vector functions
Mathematical Functions
floor(1.4)
Log()
Takes the logarithm of x with base y; if base is not specified,
returns the natural logarithm.
you can take the logarithm of the numbers from 1 to 3
log(1:3)
• Whenever you use one of these functions, R calculates the
natural logarithm if you don’t specify any base.
• You calculate the logarithm of these numbers with base 6 like
this.
• log(1:3,base=6)
trunc(x) and round(x, digits=n)