x <- 1:25Classwork 3
Descriptive Statistics
Question 1.
- Write an R code to calculate the standard deviation (SD) of the integer vector
xbelow manually. That is to calculate the SD without using thesd()or thevar()functions.
- Also, write an R code to test whether the standard deviation you calculate manually above is equal to
sd(x).
Answer:
sd() calculates the sample standard deviation, so divide the sum of squared deviations from the mean by n - 1 before taking the square root. The code below calculates every step without using sd() or var() for the manual result.
n <- length(x)
x_mean <- sum(x) / n
squared_deviations <- (x - x_mean)^2
sum_squared_deviations <- sum(squared_deviations)
manual_sd <- sqrt(sum_squared_deviations / (n - 1))
manual_sd[1] 7.359801
sd(x)[1] 7.359801
manual_sd == sd(x)[1] TRUE
Here, n is 25, the mean is 13, and the squared deviations add to 1,300. Therefore, the sample standard deviation is \sqrt{1300/24} \approx 7.3598. The final expression manual_sd == sd(x) returns TRUE, confirming that the manual calculation agrees with sd(x).
Question 2.
- Write an R code to calculate the range (difference between the maximum and minimum values) of the vector
temp <- c(22, 28, 31, 25, 29).
temp <- c(22, 28, 31, 25, 29)Answer:
Subtract the lowest temperature from the highest temperature to get the range as a single number.
temp_range <- max(temp) - min(temp)
temp_range[1] 9
The maximum is 31 and the minimum is 22, so the range is 31 - 22 = 9. This is the spread between the two extremes, in the same units as temp.
Question 3.
- Consider the vector
scores <- c(12, 7, 15, 10, 20, 18, 5, 14). Write an R code to calculate the first quartile (Q1), median (Q2), and third quartile (Q3) using thequantile()function. Also, calculate the interquartile range (IQR).
scores <- c(12, 7, 15, 10, 20, 18, 5, 14)Answer:
Ask quantile() for the 25th, 50th, and 75th percentiles. Then subtract Q1 from Q3 to calculate the interquartile range.
quartiles <- quantile(scores, probs = c(0.25, 0.50, 0.75)) # a named vector
quartiles 25% 50% 75%
9.25 13.00 15.75
iqr <- quartiles[3] - quartiles[1]
iqr <- as.numeric(iqr) # to remove the percentile label
iqr[1] 6.5
# Check the calculation against R's built-in IQR() function
iqr == IQR(scores)[1] TRUE
The sorted scores are 5, 7, 10, 12, 14, 15, 18, 20. With R’s default interpolation method, Q1 is 9.25, the median (Q2) is 13, and Q3 is 15.75. The IQR is 15.75 - 9.25 = 6.5; it describes the spread of the middle half of the scores. as.numeric() removes the percentile label from the single IQR value.
