Working with numbers

R basics
Numbers
Summarize
Author

Karen C. Goncalves dos Santos

Published

October 2, 2023

Functions for numeric data

Sum, mean and median

You can obtain the sum, mean and median by calling the functions sum(), mean(), median(), respectively. You need to include na.rm=T to obtain the estimate when you have missing values in the data.

numeric_vector = c(iris$Sepal.Length, NA, NA)
sum(numeric_vector)
[1] NA
sum(numeric_vector, na.rm = T)
[1] 876.5
median(numeric_vector)
[1] NA
median(numeric_vector, na.rm = T)
[1] 5.8
mean(numeric_vector)
[1] NA
mean(numeric_vector, na.rm = T)
[1] 5.843333

Standard deviation, variance and interquantile range

For the data dispersion, you can use the functions sd() (standard deviation), var() (variance) and IQR() (interquantile range). Remember to use na.rm=T.

Variance calculation

Variance = \(\sum\) \(( x - mean )^2\) / N

Where

  • x is each and every value of the input vector
  • mean is the mean of the input vector
  • N is the length of the input vector
Standard deviation calculation

Std.Dev = \(\sqrt{Variance}\)

Interquantile range calculation

IQR(x) = quantile(x, 3/4) - quantile(x, 1/4)

numeric_vector = c(iris$Sepal.Length, NA, NA)
sd(numeric_vector)
[1] NA
sd(numeric_vector, na.rm = T)
[1] 0.8280661
var(numeric_vector)
[1] NA
var(numeric_vector, na.rm = T)
[1] 0.6856935
#IQR(numeric_vector) Not accepted when there are NA values
IQR(numeric_vector, na.rm = T)
[1] 1.3

Column-wise and row-wise summaries

You can calculate the sum and mean for each row/column of a numeric data frame with the functions:

  • Sum: colSums and rowSums/rowsum
  • Mean: colMeans and rowMeans
Back to top