#Question: How would I create a function in r to take the mean of all the elements in a vector?
##This is where I define the function and its arguments and methods. I set an iterative variable called “sumx” to 0 and then ran a for loop which iterated for each element in the argument vector. Each element in the argument vector, i, was added to the iterative variable sum for each element in the vector. Lastly, I divided the iterative variable sumx by the length of the vector to determine the mean. I then printed the output.
vector.mean <- function(x)
{
sumx <- 0
for(i in x){
if (class(i) == "character")
{next}
else if (is.na(i) == TRUE)
{next}
sumx <- sumx + i
}
function.mean <- sumx/length(x)
print(function.mean)
}
##Testing Function Works
## [1] 856.7
###Running the function on package data
#Loading Data We will be using the same package and data as Dr. Brouwer’s example, “palmerpenguins”
#install.packages("palmerpenguins")
library(palmerpenguins)
## Warning: package 'palmerpenguins' was built under R version 4.1.2
data(penguins)
#Creating a vector with palmerpenguins information We’ll work with the data in the body mass and bill length columns. We will assign the data in those columns to the variables X & Y respectively. We will then convert the dataframe columns into vectors using the c() function
X <- penguins$body_mass_g
Y <-penguins$bill_length_mm
X <- c(X)
Y <- c(Y)
#Running the function
vector.mean(X)
## [1] 4177.326
vector.mean(Y)
## [1] 43.66657
Note that the echo = FALSE parameter was added to the code chunk to prevent printing of the R code that generated the plot.