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.

Solution: Input and Output from .txt File

Press + to interact
main.r
data.txt
mean <- function(myVector) # Creating function to find the mean
{
# The formula for finding mean is sum / 2
sum = 0
myOutputVector <- 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 vector
sortedVector=sort(as.integer(myVector)) # sort is a built in function. You can write your own soretd function as well
myVectorLength = length(myVector)
middle = myVectorLength / 2
if (myVectorLength%%2==0)
{
return((sortedVector[middle]+sortedVector[middle+1])/2)
}
else
{
return(sortedVector[ceiling(middle)])
}
}
# Driver Code
path <- "data.txt" # path of the input file
fileData <- file(path, open = "r") # open the file
lines <- readLines(fileData) # read all the lines present in the file
myVector <- vector("numeric", 0) # create empty vector to save all values
for (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 result
myMedian = median(myVector) # find median
myMean = mean(myVector) # find mean
result <- c(result, myMean) # concatenate mean and median in the result
result <- 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 and median using their functions and store the output in the result vector.

  • Line number 47: Write the result vector on output/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.