<- function(intgr) {
odd_even if (intgr %% 2 == 0) {
print("even")
else {
} print("odd")
}
}
odd_even(3)
[1] "odd"
Functions in R are defined using the keyword function()
. All the statements within a function are enclosed with {}
braces. Look at the function defined below. It takes an integer as an argument, and prints whether the integer is odd or even.
<- function(intgr) {
odd_even if (intgr %% 2 == 0) {
print("even")
else {
} print("odd")
}
}
odd_even(3)
[1] "odd"
Write a function that returns all prime numbers between \(a\) and \(b\), where \(a\) and \(b\) are parameters of the function.
<- function(a, b) {
prime <- c()
prime_numbers for (number in a:b) {
= 1
prime
for (factor in 2:(number - 1)) {
if (number %% factor == 0) {
= 0
prime
}
}
if (prime == 1) prime_numbers <- c(prime_numbers, number)
}return(prime_numbers)
}prime(40, 60)
[1] 41 43 47 53 59