Functions in R programming language
In R programming, functions allow you to encapsulate a block of code and reuse it multiple times with different inputs and outputs. Functions can take one or more arguments as input and return one or more values as output.
The basic syntax for defining a function in R is as follows:
function_name <- function(arg1, arg2, ...) {
# code to be executed
return(output)
}
Here, function_name is the name of the function, arg1, arg2, and so on are the arguments that the function takes as input, and output is the value that the function returns as output.
For example, the following code defines a function add_numbers that takes two arguments and returns their sum:
add_numbers <- function(x, y) {
z <- x + y
return(z)
}
You can call this function with different inputs to get different outputs:
result1 <- add_numbers(2, 3) # result1 is 5
result2 <- add_numbers(10, -5) # result2 is 5
Functions can also be used to modify data structures or perform complex operations. For example, the following function takes a vector of numbers as input and returns the sum of the squares of all the even numbers in the vector:
sum_even_squares <- function(x) {
return(sum(x[x %% 2 == 0]^2))
}
You can call this function with a vector of numbers to get the sum of the squares of the even numbers in the vector:
my_vector <- c(1, 2, 3, 4, 5)
result <- sum_even_squares(my_vector) # result is 20 (2^2 + 4^2)
print(result)
Functions are an essential tool for programming in R, allowing you to create modular, reusable code that can be used in multiple contexts. By defining functions that encapsulate specific operations or algorithms, you can write code that is easier to read, debug, and maintain.
Try it yourself from this R programming tool here.
Latest Post
Information retrieval – Searching of text using Elasticsearch
Information retrieval is the process of obtaining relevant information resources from the collection of resources relevant to information need.
Learn more