Module # 2 Assignment
Evaluate myMean Function
- Use the vector:
assignment2 <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22) - Consider this function:
myMean <- function(assignment2) { return(sum(assignment) / length(someData)) } assignment2 <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)- myMean <- function(assignment2) {return(sum(assignment) / length(someData))}
- myMean(assignment2)
- Error in sum(assignment) : object 'assignment' not found
The function fails due to incorrect variable names inside the function body.
-
The function argument is named
assignment2 -
Inside the function, the variables
assignmentandsomeDataare used -
These variables do not exist within the function or the global environment
Corrected Version of
myMean()Testing the Corrected Function
Correct Output
-
Reflection
This exercise helped reinforce how important variable naming and scope are when writing functions in R. Even though the data existed outside the function, R could not recognize incorrectly named variables inside the function body. Debugging this issue made it clear that functions only work with the objects explicitly passed to them. Understanding this concept will help me write cleaner, more reusable code and avoid common errors in future data analysis assignments.
Comments
Post a Comment