Solution Review: Find Mean and Median
In this review, we give a detailed analysis of the solution to the problem of finding mean and median.
We'll cover the following
Solution: Input and Output from .txt
File
mean <- function(myVector) # Creating function to find the mean{# The formula for finding mean is sum / 2sum = 0myOutputVector <- vector("integer", 0)for(i in myVector){sum = sum + as.integer(i) # sum all the values in the vector}return(sum / length(myVector)) # return the mean}median <- function(myVector) # Creating function to find the median{# median is the middle value of the sorted vectorsortedVector=sort(as.integer(myVector)) # sort is a built in function. You can write your own soretd function as wellmyVectorLength = length(myVector)middle = myVectorLength / 2if (myVectorLength%%2==0){return((sortedVector[middle]+sortedVector[middle+1])/2)}else{return(sortedVector[ceiling(middle)])}}# Driver Codepath <- "data.txt" # path of the input filefileData <- file(path, open = "r") # open the filelines <- readLines(fileData) # read all the lines present in the filemyVector <- vector("numeric", 0) # create empty vector to save all valuesfor (i in 1:length(lines)){myVector <- c(myVector, lines[i]) # concatenate the values in this vector}result <- vector("numeric", 0) # create empty vector to store the resultmyMedian = median(myVector) # find medianmyMean = mean(myVector) # find meanresult <- c(result, myMean) # concatenate mean and median in the resultresult <- c(result, myMedian)write(result, "output/outData.txt") # write the result in the respective file
Explanation
This solution is a bit tricky, but don’t worry we will break it down for you.
Let’s begin from the driver code (line number 29).
Steps Performed:
-
Line number 30 - 32: Open the file and fetch all the lines in a variable.
-
Line number 34 - 38: Populate a vector to store inputs from the file.
-
Line number 40: Create a
result
vector. -
Line number 41 - 45: Find
mean
andmedian
using their functions and store the output in theresult
vector. -
Line number 47: Write the
result
vector onoutput/outData.txt
file.
mean()
and median()
functions are simple. They just take a vector, iterate over all the elements, and output the specific answer.
In the next lesson, we have another challenge for you to solve.