In R, a function is a block of code that performs a specific task and returns a result. Functions are defined using the function() keyword, and can take one or more arguments as input. Functions are designed to be reusable and modular, and can be called from other parts of the code. In contrast, a script is a series of R commands that are executed in order to perform a specific task. Scripts are typically written to automate a series of tasks or to perform a data analysis.
Here’s an example of a function in R:
# Defining a function
my_function <- function(x, y) {
z <- x + y
return(z)
}
# Calling the function
my_function(2, 3)
# Returns 5
In this example, we define a function called my_function that takes two arguments, x and y, adds them together, and returns the result as z. We then call the function with the arguments 2 and 3, and the function returns the value 5.
Here’s an example of a script in R:
# Loading a data file
my_data <- read.csv("my_data.csv")
# Calculating the mean of a variable
mean_variable <- mean(my_data$variable)
# Printing the result
print(mean_variable)
In this example, we load a data file using the read.csv() function, calculate the mean of a variable using the mean() function, and print the result using the print() function. This series of commands can be saved as a script and executed in order to perform the specified tasks.
In summary, functions and scripts are both important parts of the R programming language, but they serve different purposes. Functions are reusable blocks of code that perform a specific task and return a result, while scripts are a series of commands that are executed in order to perform a specific task or automate a series of tasks. Functions are designed to be modular and reusable, while scripts are typically written to perform a specific task or analysis.