In R, a function is a block of code that performs a specific task. You can define your own functions in R.
# A simple function to add two numbers
add_numbers <- function(x, y) {
return(x + y)
}
# Call the function
add_numbers(5, 10)
## [1] 15
square_number that takes a
number as input and returns its square.# Your code here
square_number <- function(x){
return(x^2)
}
square_number(3)
## [1] 9
get_greeting that takes a name
as input and returns a greeting message (e.g., “Hello, Charlie!”).# Your code here
get_greeting <- function(name){
return(paste("Hello",name,"!"))
}
get_greeting("Alif")
## [1] "Hello Alif !"
calculate_mean that takes a
numeric vector as input and returns its mean.# Your code here
calculate_mean <- function(numbers){
return(mean(numbers))
}
calculate_mean(c(1,2,3,4,5))
## [1] 3
# Your code here
sum_integers <- function(int1, int2){
return(int1+int2)
}
sum_integers(1,2)
## [1] 3
TRUE if a given
integer is inside a vector.# Your code here
is_in_vector <- function(int, vec){
return(int %in% vec)
}
is_in_vector(2, c(1,2,3))
## [1] TRUE
is_in_vector(2, c(1,4,3))
## [1] FALSE
# Your code here
my_df <- data.frame(
ID = 1:3,
Name = c("A", "B", "C"),
Value = c(10.5, 20.1, 30.0)
)
name_and_class <- function(df){
for (col_name in names(df)) {
cat(col_name,"is",class(df[[col_name]]),"\n")
}
}
name_and_class(my_df)
## ID is integer
## Name is character
## Value is numeric
# Your code here
count_occurrences <- function(vector, integer) {
return(sum(vector == integer))
}
count_occurrences(c(1, 2, 2, 3, 2, 4), 2)
## [1] 3
print(c(1, 2, 2, 3, 2, 4) == 2)
## [1] FALSE TRUE TRUE FALSE TRUE FALSE
# Your code here
analyze_vector <- function(vector) {
cat("Mean:", mean(vector), "\n")
cat("Standard Deviation:", sd(vector), "\n")
if (length(vector) %% 2 != 0) {
cat("Median:", median(vector), "\n")
}
}
analyze_vector(c(1, 2, 3, 4, 5))
## Mean: 3
## Standard Deviation: 1.581139
## Median: 3
analyze_vector(c(1, 2, 3, 4, 5, 6))
## Mean: 3.5
## Standard Deviation: 1.870829
# Your code here
find_divisors <- function(n) {
divisors <- c()
if (n > 3) {
for (i in 2:(n - 1)) {
if (n %% i == 0) {
divisors <- c(divisors, i)
}
}
}
cat("Divisors of", n, ":", divisors, "\n")
return(length(divisors))
}
find_divisors(12)
## Divisors of 12 : 2 3 4 6
## [1] 4
find_divisors(7)
## Divisors of 7 :
## [1] 0
NA.# Your code here
replace_with_na <- function(df, value) {
df[df == value] <- NA
return(df)
}
my_df_2 <- data.frame(
A = c(1, 2, 3),
B = c("x", "y", "x")
)
print(my_df_2)
## A B
## 1 1 x
## 2 2 y
## 3 3 x
replace_with_na(my_df_2, "x")
## A B
## 1 1 <NA>
## 2 2 y
## 3 3 <NA>
replace_with_na(my_df_2, 2)
## A B
## 1 1 x
## 2 NA y
## 3 3 x