Lesson 2 of 8 · 8 min

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

  1. Create temps with this week's temperatures: 24, 27, 31, 29, 22, 25, 30.
  2. Create fahrenheit: every temperature converted with * 9 / 5 + 32, in one line.
  3. Print Mean: 26.9 (the mean, rounded to 1 decimal) and Max: 31.
script.R
# 1. temps


# 2. fahrenheit


# 3. print the mean and the max

R 4.5 runs right here in your browser. The first run downloads about 25 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…