R Median
The median in R is calculated using the median()
function. It represents the middle value in a sorted list of numbers and is less affected by outliers than the mean.
Key Topics
Median Example
# Calculating the median
values <- c(10, 20, 30, 40, 50)
median_value <- median(values)
print(median_value)
Output:
[1] 30
Code Explanation: The median()
function calculates the middle value of the sorted vector values
, which is 30.
Handling NA Values in Median
Use the na.rm = TRUE
argument to ignore NA
values when calculating the median.
# Calculating median with NA values
values_with_na <- c(10, 20, NA, 40, 50)
median_value <- median(values_with_na, na.rm = TRUE)
print(median_value)
Output:
[1] 30
Code Explanation: The na.rm = TRUE
argument removes NA
values before calculating the median.
Key Takeaways
- The
median()
function calculates the middle value of a numeric vector. - Use
na.rm = TRUE
to ignoreNA
values. - The median is useful for understanding the central tendency when the data contains outliers.