R Vector and Function

Hello, today I have a simple example to show you how I have created a simple R function that will display the mean or average from a vector.

I am creating a vector variable called ‘assignment2.’ Having variables assigned like this will make calculations easier. 

assignment2<- c(6,18,14,22,27,17,22,20,22)  

Now, I am ready to calculate the mean of the ‘assignment2’ vector.

The function will calculate the sum of assignment2 array of numbers then by dividing by the length of the vector (168/9), I will get the mean or average as the result.

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

Since I wanted produced an output, the function used the return() function within.

Now, let me call the function using the vector as the argument to see the results:

myMean(assignment2) 

This is is the result:

[1] 18.66667

Note: the below calculation will do the same thing as the function (above); however, using functions helps me avoid redundant code by centralizing logic in a single location. Thus, I will reduce duplication and make my code shorter and more efficient.

sum(assignment2)/length(assignment2)

[1] 18.66667

Creating vectors and functions makes my code more organized and easier to maintain. Moreover, I can reuse the function across different projects, saving time and effort.

One thought on “R Vector and Function

Leave a comment