24 lines
1.2 KiB
R
24 lines
1.2 KiB
R
#Create two vectors with random, normal distribution numbers: one with even, and another with odd number of elements.
|
|
bunch_of_nums_even <- rnorm(100)
|
|
bunch_of_nums_odd <- rnorm(101)
|
|
#Sort one of the vectors according to number size
|
|
sorted_nums <- sort(bunch_of_nums_even) #< I used even for this example - switch to odd to test that as well.
|
|
num_length <- length(sorted_nums)
|
|
#If the length of the sorted vector is divisble by 2...
|
|
if ((num_length %% 2) == 0) {
|
|
print("Vector is even")
|
|
#... create a vector of the 2 middle elements...
|
|
num_medians <- c((num_length/2),((num_length/2)+1))
|
|
#... and calculate their average; that is the mean.
|
|
num_median <- mean(sorted_nums[num_medians])
|
|
# ^ This is a vector of the 2 middle spots in our even vector
|
|
} else #< If the length of the sorted vector is odd...
|
|
{
|
|
print("Vector is odd")
|
|
#Get the index of the median number by substracting 1 from the total count, divide by half and add one again.
|
|
num_median_index <- (((num_length + 1)/2)) #<There's probably a better way to do this.
|
|
#The median is the number in the index we figured out earlier; pull it from the sorted vector.
|
|
num_median <- sorted_nums[num_median_index]
|
|
}
|
|
cat("Median is:", num_median)
|