Assignment 2

 

Assignment 2 - Importing Data and Function Evaluation in R



For this part of the assignment, I tested the provided myMean function in RStudio, carefully recorded the errors that appeared, explained why they happened, and then corrected the code so it would successfully return the mean of the given dataset.

Original Code: 

assignment2 <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22)
myMean <- function(assignment2) { 
     return(sum(assignment) / length(someData)) 

Errors from Testing

Error 1:

> return(sum(assignment) / length(someData)) 
Error: object 'assignment' not found 

Inside the function body, the code used assignment instead of assignment2. Since no variable named assignment exists, R could not evaluate the expression and produced this error.

Error 2:

> return(sum(assignment2) / length(someData)) 
Error: object 'someData' not found 

Here, assignment2 was corrected in the sum() part, but the denominator still referred to someData, which was never defined. R looked for someData and failed, so it produced this error.

Error 3:

> return(sum(assignment2) / length(assignment2)) 
Error: no function to return from, jumping to top level 

return() only works inside a function, so running it directly in the console causes an error. Once it’s placed inside myMean(), calling myMean(assignment2) executes properly and returns 19.25.

Corrected Code: 

assignment2 <- c(16, 18, 14, 22, 27, 17, 19, 17, 17, 22, 20, 22) 
myMean <- function(assignment2) { 
     return(sum(assignment2) / length(assignment2)) 
myMean(assignment2) 

Output:

[1] 19.25 

  • sum(assignment2) adds all the values in the vector.
  • length(assignment2) counts how many numbers are in the vector.

The formula for the mean is:

mean sum of values number of values​

For this dataset:

mean= (16+18+14+22+27+17+19+17+17+22+20+22) / 12=19.25





Comments

Popular posts from this blog

Assignment 3

Installation Report