For this week’s assignment, I explored some foundational R concepts, specifically writing and debugging functions. The task asked me to test a custom function called myMean on a provided dataset and then explain why it failed or succeeded.
The Dataset
assignment2 <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
The Original Function
myMean <- function(assignment2) {
return(sum(assignment) / length(someData))
}
Testing the Function
When I ran:
myMean(assignment2)
I received the following error:
Error in sum(assignment): object 'assignment' not found
Why the Function Failed
The problem is that the function body refers to variables (assignment and someData) that do not exist. The function argument is named assignment2, but the calculation inside does not use that argument consistently. Because of this mismatch, R cannot find the objects and throws an error.
Corrected Function
The fix is straightforward: use the correct argument name throughout the function.
myMean <- function(assignment2) {
return(sum(assignment2) / length(assignment2))
}
Correct Output
Running the corrected function:
myMean(assignment2)
# [1] 19.25
The mean of the dataset is 19.25, which matches the result from R’s built-in mean() function.
Takeaway
This exercise highlights the importance of consistent variable naming in R. Even small mismatches can break code and produce confusing errors. Debugging in R often comes down to carefully checking object names and making sure function arguments are used correctly.
Leave a comment