Code
<- function(choice)
hello_or_mellow
{if(choice == 1)
{print("Hello World")
}if(choice == 0)
{print("Mellow World ")
} }
Functions in R allow use a set of commands that we can keep calling repeatedly. The goal of a function is to fulfill a certain task, typically relying on inputs from a user. The rest of the problems in this short book has many functions that we ask you to write, so here, we start with some simple functions.
Write a function to print Hello World
if user inputs 1 and Mellow World
if user inputs 0
<- function(choice)
hello_or_mellow
{if(choice == 1)
{print("Hello World")
}if(choice == 0)
{print("Mellow World ")
} }
Write a function to return Hello World
if user inputs 1 and Mellow World
if user inputs 0. Think about the difference between this function and that previous one.
<- function(choice)
hello_or_mellow
{if(choice == 1)
{return("Hello World")
}if(choice == 0)
{return("Mellow World ")
} }
Consider a scenario where a garden is circular, and you need to calculate the area of the garden. Write an R function that takes the radius of the garden as input and returns the area. How would you modify this function if the garden is elliptical instead of circular?
# Function to calculate area of a circular garden
<- function(radius)
calculate_circular_garden_area
{<- pi * radius^2
area return(area)
}
# Function to calculate area of an elliptical garden
<- function(radius1, radius2) {
calculate_elliptical_garden_area <- pi * radius1 * radius2
area return(area)
}
Imagine you have two sets of exam scores, one from the first midterm and the other from the second midterm. Write an R function that takes both sets of scores as inputs and returns the set with the higher average score.
<- function(scores1, scores2)
compare_average_scores
{if (mean(scores1) > mean(scores2))
{return(scores1)
else {
} return(scores2)
} }
(Not a function question) Create two vectors vec1
and vec2
, where vec1
contains 1 and Your Name while vec2
contains your JEE Advance/JAM Rank and Answer to the Question as TRUE
or FALSE
Dootika Ma’am will give all
s in this course
Can such vec1
andvec2
be constructed? If yes, what are the datatype of 1 in vec1
, and Answer to the question in vec2
? Use typeof()
function for finding out.
# Define vec1 with 1 and my name
<- c(1, "Problems")
vec1
# Define vec2 with my JEE Advanced Rank (assuming rank as 10000) and the answer to the question
<- 10000 # Replace this with your actual JEE Advanced Rank/ JAM Rank
jee_rank <- TRUE
answer
<- c(jee_rank, answer)
vec2
# Print vec1 and vec2 to verify
vec1
vec2
# Check the datatype of 1 in vec1
typeof(vec1[1])
# Check the datatype of the boolean answer in vec2
typeof(vec2[2])