Introduction
Functions help you group code to do a specific job. You can reuse them anytime without rewriting.
Functions help you group code to do a specific job. You can reuse them anytime without rewriting.
function_name <- function(arg1, arg2, ...) {
# code to run
return(value) # optional
}The function name is how you call it later.
Arguments (arg1, arg2, ...) are inputs you give to the function.
say_hello <- function() {
print("Hello!")
}add <- function(x, y) {
return(x + y)
}square <- function(num) {
num * num
}This program defines a function to greet someone by name. It then calls the function with "Anna" and prints the greeting.
greet <- function(name) {
message <- paste("Hello," , name, "!")
return(message)
}
result <- greet("Anna")
print(result)If you do not use return(), R returns the last expression automatically.
Functions help keep your code clean and easy to understand.
Functions group code to do one job.
Define with function() and give a name.
Use arguments to send inputs and return() to send back results.
greet in R?add that takes two arguments x and y in R?multiply <- function(a, b) {
result <- a * b
return(result)
}
multiply(3, 4)sum_values <- function(x, y) total <- x + y return(total) }
filter_positive that takes a numeric vector and returns only the positive numbers. Which function definition correctly does this in R?Pass the test and this pattern moves unknown