Sum, product, and range of data

Sums, differences, and products

Sum and cumulative sum

age <- c(17, 30, 30, 25, 23, 21)
sum(age)
[1] 146
cumsum(age)
[1]  17  47  77 102 125 146

Successive differences

diff(age)
[1] 13  0 -5 -2 -2
diff(age, lag=2)
[1] 13 -5 -7 -4

Product and cumulative product

prod(age)
[1] 184747500
cumprod(age)
[1]        17       510     15300    382500   8797500 184747500
factorial(5)
[1] 120

Minimum, maximum and range

Get the minimum, maximum and range

min(age)
[1] 17
max(age)
[1] 30
range(c(17, 30, 30, 25, 23, 21))
[1] 17 30
diff(range(c(17, 30, 30, 25, 23, 21)))
[1] 13

Identify the minimum and maximum elements

which.max(age)
[1] 2

Identify element closest to a value

vec <- c(-5, -8, -2, 10, 9)
val <- 0
which.min(abs(vec-val))
[1] 3

Pairwise minimum and maximum

vec1 <- c(5, 2, 0, 7)
vec2 <- c(3, 3, 9, 2)
pmax(vec1, vec2)
[1] 5 3 9 7
pmin(vec1, vec2)
[1] 3 2 0 2

Get the article source from GitHub

R markdown - markdown - R code - all posts