Module # 2 Assignment Importing Data and Function Evaluation in R
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)) } - In RStudio, run
myMean(assignment2)and record the output or error.
After running the code in R Studio this is the error that occurred:
> assignment2 <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
> 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)
The function fails because of inconsistent variable names:
-
You pass in "assignment2", but inside the function you try to use "assignment" and "someData".
-
Since neither "assignment" nor "someData" exists in your environment, R throws an error.
Essentially, the function is ignoring the input "assignment2" and instead trying to use undefined variables.
The Corrected code in R Studio to fix the error is:
#Vector
> assignment2 <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
> #Function
> myMean <- function(assignment2) {
+ return(sum(assignment) / length(someData))
+ }
> #Test Run
> myMean <- function(assignment2) {
+ return(sum(assignment2) / length(assignment2))
+ } myMean(assignment2)
[1] 19.25
Comments
Post a Comment