In module 2, the class was asked to test and evaluate R code. We were given two commands:
assignment2 <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22) myMean <- function(assignment2) { return(sum(assignment)/length(someData)) }
The first line creates a dataset labeled assignment2
, and the second line creates a function named myMean
. Judging by the code, myMean
is meant to calculate the mean of the dataset sent to it as an argument.
Unfortunately, the code doesn’t work as written, giving an object not found error. The problem lies in the variables used in the body of the function – neither assignment nor someData have been given values. If the goal is to find the mean of the dataset passed to the function as an argument, then the names of the variables in the function body should match that of the function’s argument.
The function works, then, if it’s rewritten as:
myMean <- function(assignment2) { return(sum(assignment2)/length(assignment2)) }
For clarity it might make sense to change the argument of the function to assignment
instead of assignment2
. That way there wouldn’t be a potential for confusion between the global variable and the internal variable processed by the function. Because of the scope difference, however, the identical names don’t create a problem for the result – passing a different dataset to the function causes it to return the mean of that dataset, not the dataset contained in the global assignment2
variable.