Arguments inside function() and return() used [OK]
Hint: Put arguments inside function() parentheses [OK]
Common Mistakes:
Placing arguments outside function()
Missing braces {} around function body
Incorrect assignment syntax
3. What will be the output of the following R code?
multiply <- function(a, b) {
result <- a * b
return(result)
}
multiply(3, 4)
medium
A. 12
B. 7
C. 34
D. Error
Solution
Step 1: Understand function behavior
The function multiply takes two numbers and returns their product.
Step 2: Calculate the product of 3 and 4
3 * 4 equals 12, so the function returns 12.
Final Answer:
12 -> Option A
Quick Check:
3 * 4 = 12 [OK]
Hint: Multiply inputs and return result to get output [OK]
Common Mistakes:
Adding instead of multiplying
Concatenating numbers as strings
Forgetting to return the result
4. Identify the error in this R function definition:
sum_values <- function(x, y)
total <- x + y
return(total)
}
medium
A. Function name is invalid
B. Missing opening brace { after function()
C. Incorrect use of return()
D. Arguments should be inside square brackets []
Solution
Step 1: Check function body braces
The function body must be enclosed in braces { } immediately after function() declaration.
Step 2: Locate missing brace
The code lacks an opening brace { after function(x, y), causing syntax error.
Final Answer:
Missing opening brace { after function() -> Option B
Quick Check:
Function body needs { } [OK]
Hint: Always put { after function() to start body [OK]
Common Mistakes:
Omitting braces around function body
Placing return outside function
Using wrong brackets for arguments
5. You want to write a function filter_positive that takes a numeric vector and returns only the positive numbers. Which function definition correctly does this in R?
hard
A. filter_positive <- function(vec) { return(vec[vec == 0]) }
B. filter_positive <- function(vec) { return(vec[vec < 0]) }
C. filter_positive <- function(vec) { vec > 0 }
D. filter_positive <- function(vec) { return(vec[vec > 0]) }
Solution
Step 1: Understand filtering in R
To get positive numbers, select elements where vec > 0.
Step 2: Check return statement
filter_positive <- function(vec) { return(vec[vec > 0]) } returns vec elements where condition vec > 0 is TRUE, correctly filtering positives.