Descriptive statistics: mean, median, mode, standard deviation, variance in R

In R, you can easily calculate descriptive statistics such as mean, median, mode, standard deviation, and variance using built-in functions. Here are some examples:

## Mean
x <- c(1, 2, 3, 4, 5) mean(x) # Output: 3 ## Median y <- c(1, 2, 3, 4, 50) median(y) # Output: 3 ## Mode z <- c(1, 2, 2, 3, 3, 3, 4, 4, 4, 4) Mode <- function(x) { ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] } Mode(z) # Output: 4 ## Standard deviation x <- c(1, 2, 3, 4, 5) sd(x) # Output: 1.581139 ## Variance x <- c(1, 2, 3, 4, 5) var(x) # Output: 2.5 In the code above, we first create vectors of numeric data for each of the statistics we want to calculate. We then use the built-in R functions to calculate the mean, median, standard deviation, and variance. For the mode, we define a custom function `Mode()` that uses the `match()` function to find the index of each unique valuein the vector, and then uses the `tabulate()` function to count the number of occurrences of each value. Finally, it returns the value with the highest count. Note that R also has built-in functions for other descriptive statistics such as range, quartiles, and interquartile range, among others. You can find more information on these functions in the R documentation or online tutorials and resources.