...

/

Solution Review: Find Mean and Median

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
R
Files
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 ...