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 assignment and someData are used

    • These variables do not exist within the function or the global environment

    Corrected Version of myMean()

    myMean <- function(assignment2) { sum(assignment2) / length(assignment2) }

    Testing the Corrected Function

    myMean(assignment2)

    Correct Output

    [1] 19.25
  • 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

Popular posts from this blog

ABC vs. CBS: Comparing Fictional Presidential Poll Data in R

Assignment #10: Building Your Own R Package

Module # 4 Programming structure assignment