0
0
R Programmingprogramming~20 mins

Function definition in R Programming - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Function Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple function call
What is the output of the following R code?
R Programming
multiply_by_two <- function(x) {
  return(x * 2)
}

result <- multiply_by_two(5)
print(result)
A[1] 10
B[1] 7
CError in multiply_by_two(5) : could not find function "multiply_by_two"
D[1] 25
Attempts:
2 left
💡 Hint
Think about what the function does to the input number.
Predict Output
intermediate
2:00remaining
Function with default argument
What will be printed when this R code runs?
R Programming
greet <- function(name = "Guest") {
  print(paste("Hello," , name))
}

greet()
greet("Alice")
A
[1] "Hello, Guest"
[1] "Hello, Alice"
B
[1] "Hello, "
[1] "Hello, Alice"
CError: object 'name' not found
D
[1] "Hello, Alice"
[1] "Hello, Guest"
Attempts:
2 left
💡 Hint
Check what happens when no argument is given.
Predict Output
advanced
2:00remaining
Function with variable scope
What is the output of this R code?
R Programming
x <- 10

add_to_x <- function(y) {
  x <- 5
  return(x + y)
}

result <- add_to_x(3)
print(result)
print(x)
A
[1] 13
[1] 10
B
[1] 8
[1] 10
C
[1] 8
[1] 5
D
[1] 13
[1] 5
Attempts:
2 left
💡 Hint
Remember that variables inside functions have local scope.
Predict Output
advanced
2:00remaining
Function with missing return statement
What will this R code print?
R Programming
sum_values <- function(a, b) {
  a + b
}

result <- sum_values(4, 6)
print(result)
AError: object 'result' not found
BNULL
C[1] 10
D[1] 46
Attempts:
2 left
💡 Hint
In R, the last expression is returned even without return().
🧠 Conceptual
expert
2:00remaining
Error type from incorrect function call
What error will this R code produce when run?
R Programming
my_function <- function(x, y) {
  return(x + y)
}

my_function(5)
ANo error, returns 5
BError in my_function(5) : object 'y' not found
CWarning: unused argument (5)
DError in my_function(5) : argument "y" is missing, with no default
Attempts:
2 left
💡 Hint
Check if all required arguments are provided.