Vectors
In R, almost everything is a vector: an ordered collection of values of the same type. Even a single number is a vector of length 1, which is why R prints [1].
Make a vector with c() ("combine"):
prices <- c(1.5, 2.0, 0.8, 3.2)
length(prices) # [1] 4
Vectorised arithmetic
Arithmetic on a vector applies to every element. No loop needed:
prices * 2 # [1] 3.0 4.0 1.6 6.4
prices + c(1, 1, 1, 1) # element by element
prices > 1.6 # [1] FALSE TRUE FALSE TRUE
This is the heart of R: you describe the calculation once and R applies it to the whole column of data.
Summaries
sum(prices) # 7.5
mean(prices) # 1.875
max(prices) # 3.2
min(prices) # 0.8
sort(prices) # smallest to largest
rev(prices) # reversed
Sequences: 1:5 gives 1 2 3 4 5; seq(0, 100, by = 25) gives 0 25 50 75 100.
Your task
- Create
tempswith this week's temperatures: 24, 27, 31, 29, 22, 25, 30. - Create
fahrenheit: every temperature converted with* 9 / 5 + 32, in one line. - Print
Mean: 26.9(the mean, rounded to 1 decimal) andMax: 31.