Basic R function and Data Structure

Hey everyone!

I explored R functions using a simple one from this week’s assignment to calculate the mean of a numeric vector. Initially, the function was straightforward: sum up the values and divide by the count. Running the function gave me a result of 19.25—pretty cool, right?

The function provided by Professor myMean() worked because it first sums the numeric vector (sum(assignment2)), then counts the elements using length(assignment2).

The function divides the total sum by the count to obtain the mean. It uses the return() function to ensure the calculated mean is returned when it is called. This approach is efficient for numeric data without missing values or non-numeric entries.

However, I wanted to take it further, so I modified the original one (myMean()) and added checks to ensure the input was numeric and not empty, preventing errors before they happened. Now, my function is not only functional but also more flexible and scalable for different scenarios.

For instance, when I test with non-numeric data using R’s built-in mean() function, I get:

With the custom function, the error message is clearer

This customization allows me to provide specific feedback to users while keeping the function flexible.

R’s built-in mean() does the same job globally, but writing custom functions helps me gain greater control, flexibility, and the ability to expand the function capabilities based on the project’s needs.

Want to see the code? Check it out on my GitHub: GitHub: Module 2 Assignment.

Let me know your thoughts

Leave a comment