R from scratch — the console as a calculator, variables, vectors and matrices (and the day c(1, 2) + c(1, 2, 3) barely complained)

In R almost everything is a vector, even when it does not look like one: a single number is a vector of length 1, and understanding that saves you half the scares of Statistical Methods I.

I learnt it in the first ME1 lab. I had to subtract the group mean from each mark and, instead of the mean, I subtracted a two-value vector by mistake. R did not stop with an error: it gave me a result, left a red line starting with «Warning message» and I carried on as if nothing had happened. Twenty minutes later I had an impossible variance and no clue where it came from. Today I know that red line was telling me everything.

In this article we start from zero: R as a calculator, variables, data types, vectors (the piece that drives everything) and matrices. All with examples of marks and tables like the ones you will see in ME1, and every output is the real one.

What you need and the map of this topic. You do not need to have programmed before: it is enough to know what a mean is and to have R at hand (the next section tells you where). If you come from Python, three things will feel odd at first: here you count from 1, you assign with an arrow and you almost never need a loop. The topic goes in this order: first R as a calculator and variables (storing a number under a name); then the data types; then the central piece, the vector, and the four things you do with it (create it, pick elements, operate and summarise); and finally matrices, which are vectors laid out in rows and columns, with a contingency table like the ones in ME1. Almost all the way through we use the same example: 8 lab marks, from 3.75 to 9. If you get lost at any point, go back to them and ask yourself what happens to each mark.

Before you start: where to write R

You have two options and both work for this article:

  • RStudio, the program used in the labs. If you do not have it yet, the guide Install R and RStudio gets it ready in no time, and How to use RStudio shows you its four panes.
  • The site’s R playground, which runs in the browser with nothing to install. It is the same R (version 4.6), with its console, its variables pane and its plots.

Both have a console, the line starting with >, where you type a command, press Enter and R answers. And both have a script, an .R file where you write several lines to save them and run them whenever you want. To try loose things, the console. For a lab, always a script.

One more thing: in R, everything after # on a line is a comment. R ignores it, but you (and whoever marks your lab) do not.

The console as a calculator

Let us start with the simplest thing. Each line is a sum and R prints the result:

3 + 4 * 2      # multiplication first, as in maths
(3 + 4) * 2    # brackets change the order
2^10           # power: 2 to the 10th
17 / 5         # normal division, with decimals
17 %/% 5       # integer division: how many times 5 fits into 17
17 %% 5        # the remainder of that division

Output:

[1] 11
[1] 14
[1] 1024
[1] 3.4
[1] 3
[1] 2

Each result comes with a [1] in front. It is not part of the number: it is the position of the first value on that output line. Right now it looks like decoration, but as soon as a result has 30 values and does not fit on one line, that number tells you which position you are at.

Let us check the last two by hand: 5 fits 3 times into 17 (5 × 3 = 15) and 2 are left over. That is why 17 %/% 5 gives 3 and 17 %% 5 gives 2. The remainder is useful for lots of things; for example, a number is even if n %% 2 is 0.

OperatorWhat it doesExampleResult
+ - * /Addition, subtraction, product and division17 / 53.4
^Power2^101024
%/%Integer division17 %/% 53
%%Remainder of the division17 %% 52

Mathematical functions

For anything that is not a basic operation, R has functions: a name followed by brackets with the data inside.

sqrt(81)                  # square root
exp(1)                    # the number e
log(100)                  # careful! NATURAL logarithm (ln)
log(100, base = 10)       # base-10 logarithm
log10(1000)               # shortcut for base 10
round(3.14159, 2)         # rounds to 2 decimals
abs(-7)                   # absolute value
factorial(5)              # 5! = 5 · 4 · 3 · 2 · 1
choose(5, 2)              # combinations of 5 elements taken 2 at a time

Output:

[1] 9
[1] 2.718282
[1] 4.60517
[1] 2
[1] 3
[1] 3.14
[1] 7
[1] 120
[1] 10

Look at log(100): it gives 4.60517, not 2. In R, log is the natural logarithm (the ln on your calculator). If you want the base-10 one, log10 or log(x, base = 10).

Using log() thinking it is the base-10 logarithm. In ME1 you will see log in data transformations and in likelihood functions, and it is almost always the natural one. If the exercise says «base-10 logarithm», write log10().

factorial and choose are not there by chance: they are the combinatorial numbers you will use in probability. choose(5, 2) counts how many ways you can pick 2 elements out of 5 (5 · 4 / 2 = 10), exactly what appears in the binomial distribution.

Variables: storing a result with <-

A calculator that remembers nothing falls short. To store a value and use it later, you give it a name with the arrow <-:

theory_mark <- 6.5
lab_mark <- 8
final <- 0.7 * theory_mark + 0.3 * lab_mark
final

Output:

[1] 6.95

Three things happen that are worth keeping clear:

  1. Assigning prints nothing. The first three lines store values silently. To see a variable, type its name (the fourth line).
  2. The calculation uses the stored values. 0.7 × 6.5 = 4.55 and 0.3 × 8 = 2.4; added up, 6.95. It checks out.
  3. The arrow reads as «gets»: final gets the result of the calculation.

final = 0.7 * ... also works, and you will see both forms online. In R, <- is used by convention and because it makes it clear that it is an assignment (the = is kept for function arguments, as in log(100, base = 10)). In RStudio, Alt + − types the arrow with its spaces.

Use names that read on their own. lab_mark makes sense in two months; lm2 does not. You can use letters, numbers, _ and ., but a name cannot start with a number.

R is case-sensitive, and this is the most repeated mistake at the beginning:

Final

Output:

Error: object 'Final' not found

final exists, but Final is another variable you have never created. When you see object '...' not found, check how you wrote the name first.

A variable stores a value, not a formula

Before going on, an idea that is hardly ever explained and causes a lot of grief. Imagine your lab mark goes up by half a point. You change lab_mark and… does final change on its own?

theory_mark <- 6.5
lab_mark <- 8
final <- 0.7 * theory_mark + 0.3 * lab_mark
lab_mark <- lab_mark + 0.5   # the lab mark goes up by half a point
final                        # has it changed?
final <- 0.7 * theory_mark + 0.3 * lab_mark   # now yes: it is calculated again
final

Output:

[1] 6.95
[1] 7.1

The first time it still says 6.95. Line by line:

LineWhat happensWhy
1 and 26.5 and 8 are storedAssigning prints nothing
3R does the calculation with 6.5 and 8 and stores 6.95 in finalfinal gets the result, not the calculation
4lab_mark now holds 8.5The right-hand side is worked out first with the old value (8 + 0.5) and then stored on top
5Prints 6.95Nobody has recalculated final: it still holds the number from line 3
60.7 × 6.5 + 0.3 × 8.5 = 4.55 + 2.55 = 7.1The calculation is repeated, now with the new value
7Prints 7.1Now final is up to date

An R variable is not an Excel cell with its formula: it is a box with a number inside. If you change a piece of data, whatever depended on it has to be run again; that is why, if you touch something at the start of a script, you run the whole script again (in RStudio, Ctrl + Shift + Enter).

Check you’ve got it: if you now type theory_mark <- 7 and then final, what comes out?

7.1 again: final was last calculated in line 6, with 6.5 and 8.5, and changing theory_mark does not update it. For the 7 to count you have to repeat the calculation line: 0.7 × 7 + 0.3 × 8.5 = 4.9 + 2.55 = 7.45.

The basic data types

Every value has a type, and class() tells you which:

x <- 6.5
n <- 3L                      # the final L marks it as an integer
subject <- "ME1"             # text goes in quotes
passed <- final >= 5         # a comparison gives TRUE or FALSE
class(x)
class(n)
class(subject)
class(passed)
passed

Output:

[1] "numeric"
[1] "integer"
[1] "character"
[1] "logical"
[1] TRUE
TypeWhat it holdsExample
numericNumbers with or without decimals6.5, 8
integerWhole numbers (with L, or those from 1:10)3L
characterText, always in quotes"ME1"
logicalTrue or falseTRUE, FALSE

And two special values you will see a lot: NA is a missing value (a student who did not sit the exam), and NULL is nothing (an empty object).

Logicals have a trick that is gold in statistics: in a calculation, TRUE is 1 and FALSE is 0. So adding logicals counts, and their mean is a proportion:

sum(c(TRUE, FALSE, TRUE, TRUE))
mean(c(TRUE, FALSE, TRUE, TRUE))
ages <- c(19, NA, 21)
mean(ages)
mean(ages, na.rm = TRUE)

Output:

[1] 3
[1] 0.75
[1] NA
[1] 20

There are 3 TRUE out of 4, so the sum is 3 and the mean 0.75: 75 % meet the condition. And look at mean(ages): with a single NA inside, the result is NA. R does not invent the missing value; if you want to compute without it, you have to ask with na.rm = TRUE («remove the NA»). The mean of 19 and 21 is 20.

If a mean, a sum or a standard deviation gives NA for no apparent reason, there is almost certainly an NA in the data. is.na(ages) tells you in which positions.

Vectors: the piece that drives everything

A vector is a row of values of the same type. You create it with c() (for combine), and it is the structure R uses for almost everything:

marks <- c(4.5, 7, 8.25, 5, 6.5, 9, 3.75, 7.5)
length(marks)                    # how many values it has
1:8                              # from 1 to 8, one by one
seq(0, 10, by = 2.5)             # from 0 to 10 in steps of 2.5
seq(1, 2, length.out = 5)        # 5 values spread between 1 and 2
rep(c("A", "B"), times = 3)      # repeats the whole vector 3 times
rep(c("A", "B"), each = 3)       # repeats each element 3 times

Output:

[1] 8
[1] 1 2 3 4 5 6 7 8
[1]  0.0  2.5  5.0  7.5 10.0
[1] 1.00 1.25 1.50 1.75 2.00
[1] "A" "B" "A" "B" "A" "B"
[1] "A" "A" "A" "B" "B" "B"

seq and rep look like little things, but you will use them to generate the values of a variable (seq to draw a curve) and to label groups (rep). Notice the difference between times and each: in the first, the «A B» block is repeated; in the second, each letter separately.

Picking elements with square brackets

To take elements out of a vector you use square brackets [ ]. And here is the first difference with Python: R starts counting at 1, not 0.

Indices and a logical mask on an R vectorThe marks vector with positions 1 to 8, the comparison marks >= 5 with TRUE and FALSE, and the result with the 6 marks that pass.marks4.51728.253546.55963.7577.58positionmarks[1]marks >= 5FALSETRUETRUETRUETRUETRUEFALSETRUEmarks[marks >= 5]out78.2556.59out7.5The comparison gives one logical per element; the brackets keep the TRUE ones.
R counts from 1. Look at the two FALSE: 4.5 and 3.75 are left out of the filter.
marks[1]              # the first one
marks[c(2, 4)]        # the second and the fourth
marks[-1]             # all EXCEPT the first
marks >= 5            # the comparison, element by element
marks[marks >= 5]     # only those that meet the condition
which(marks >= 5)     # in which positions they are

Output:

[1] 4.5
[1] 7 5
[1] 7.00 8.25 5.00 6.50 9.00 3.75 7.50
[1] FALSE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE  TRUE
[1] 7.00 8.25 5.00 6.50 9.00 7.50
[1] 2 3 4 5 6 8

The important line is marks[marks >= 5]. Two things happen inside, as in the drawing above:

  1. marks >= 5 compares each mark with 5 and gives a vector of 8 logicals: FALSE TRUE TRUE TRUE TRUE TRUE FALSE TRUE.
  2. That vector is used as a mask: the brackets keep the values where there is a TRUE and drop the FALSE ones.

That is why 6 marks come out: 4.5 (position 1) and 3.75 (position 7) are left out. It is the way to filter data in R, and you will use it in every lab.

What you writeWhat it does
x[3]The element in position 3
x[c(1, 3)]Elements 1 and 3
x[2:5]From 2 to 5
x[-1]All but the first
x[x > 0]Those that meet the condition

Writing marks[0] thinking of the first element, as in Python. In R it does not give an error: it returns numeric(0), an empty vector, and the failure shows up three lines later with something that makes no sense.

The filter, mark by mark

So that it does not stay as «magic», this is the calculation R does inside marks[marks >= 5], position by position:

PositionMarkmarks >= 5Kept?Why
14.5FALSENo4.5 is less than 5
27TRUEYes7 is greater than 5
38.25TRUEYes8.25 is greater than 5
45TRUEYesWith >= an exact 5 gets in; with > it would be left out
56.5TRUEYes6.5 is greater than 5
69TRUEYes9 is greater than 5
73.75FALSENo3.75 is less than 5
87.5TRUEYes7.5 is greater than 5

The TRUEs are in positions 2, 3, 4, 5, 6 and 8: exactly what which(marks >= 5) returns. And since there are six TRUEs, sum(marks >= 5) would give 6, the number of passes, without filtering anything. Look at row 4: the exact 5 is the one that decides whether you write >= or >.

Check you’ve got it: what do marks[marks > 7] and which(marks > 7) return?

Each mark is compared with 7, now with «strictly greater». The 7 in position 2 does not pass, because 7 is not greater than 7. Through go 8.25 (position 3), 9 (position 6) and 7.5 (position 8). R prints [1] 8.25 9.00 7.50 (with zeros to even out the decimals) and [1] 3 6 8.

Operations work element by element

This is the idea that saves the most time in R. If you operate on a vector, the operation is done on each element, without writing any loop:

marks * 10                                      # each mark times 10
marks - mean(marks)                             # each mark minus the mean
(marks - mean(marks))^2                         # and each difference squared
sum((marks - mean(marks))^2) / (length(marks) - 1)
var(marks)                                      # R's sample variance

Output:

[1] 45.0 70.0 82.5 50.0 65.0 90.0 37.5 75.0
[1] -1.9375  0.5625  1.8125 -1.4375  0.0625  2.5625 -2.6875  1.0625
[1] 3.75390625 0.31640625 3.28515625 2.06640625 0.00390625 6.56640625
[7] 7.22265625 1.12890625
[1] 3.477679
[1] 3.477679

The first four lines are, step by step, the sample variance formula you will use in ME1: subtract the mean, square, add up and divide by n − 1. The mean is 51.5 / 8 = 6.4375; the sum of squares comes to 24.34375 and, divided by 7, gives 3.477679. The last line is the R function that does the same, and they match.

R’s var() and sd() divide by n − 1 (the corrected sample variance). If an exercise asks for the variance «of the sample» dividing by n, you will have to compute it by hand or multiply by (n − 1) / n. Always check which formula your lecturer uses.

The variance, step by step

The variance formula has five calculations inside it. Unfolded, with what each piece of the code does:

StepIn RResultWhy
1mean(marks)6.4375The sum, 51.5, divided by the 8 marks
2marks - mean(marks)−1.9375; 0.5625; …; 1.06256.4375 is subtracted from each mark (it is a vector of length 1 and gets recycled). Each number says how far that mark is from the mean, with its sign
3(marks - mean(marks))^23.75390625; 0.31640625; …Squaring stops the negatives from subtracting and makes large distances weigh more
4sum(...)24.34375The 8 squared distances are added together
5/ (length(marks) - 1)3.477679Divided by n − 1 = 7, not by 8, which is what var() does (the note above says so)

Why do we need the square in step 3? Try adding up the deviations without squaring them: you get 0. The marks below the mean (4.5, 5 and 3.75) are 6.0625 points below it in total, and the ones above, exactly 6.0625 above it. They always cancel out, with any data. Without the square, every sample would have «zero spread».

In ME1 you round to 2 decimals: the variance of these marks is 3.48 and the standard deviation, 1.86 (round(var(marks), 2)). Round only at the end: if you round the mean before subtracting, you drag that error into every calculation after it.

Check you’ve got it: why is sum(marks - mean(marks)) no good for measuring how spread out the marks are?

Because it always gives 0, whether the marks are close together or far apart. The mean is exactly the point where what is left over above makes up for what is missing below, so the positive and negative deviations cancel out. You will see it in the output of the program at the end: «Sum of deviations: 0». To measure spread you have to get rid of the sign, and the variance does it by squaring.

Recycling (and the warning you must not ignore)

What if you operate on two vectors of different lengths? R recycles the short one: it repeats it from the start until it matches the length of the long one.

Vector recycling in RTwo sums of vectors of different lengths: 4 plus 2 with no warning and 3 plus 2 with a warning; the short vector is repeated.c(1, 2, 3, 4) + c(10, 20)1234+10201020112213244 is a multiple of 2: no warningc(1, 2, 3) + c(10, 20)123+102010112213Warning message3 is not a multiple of 2: warningDashed: the values R repeats (recycles) from the short vector.
R repeats the short vector until it matches the long one. If it does not fit a whole number of times, it warns: almost always your mistake.
c(1, 2, 3, 4) + c(10, 20)
c(1, 2, 3) + c(10, 20)

Output:

[1] 11 22 13 24
[1] 11 22 13
Warning message:
In c(1, 2, 3) + c(10, 20) :
  longer object length is not a multiple of shorter object length

In the first line, 4 is a multiple of 2: c(10, 20) is repeated twice and everything fits with no warnings (1 + 10, 2 + 20, 3 + 10, 4 + 20). In the second, 3 is not a multiple of 2: R recycles anyway, gives a result (the 10 is added again to the 3) and warns with longer object length is not a multiple of shorter object length.

This is exactly what happened to me in the story at the beginning. The warning does not stop the program, so it is easy to miss, but it almost always means you have mixed two vectors that should not go together.

Ignoring Warning message lines. A warning is not an error, but in R it is often the only clue that a calculation is wrong. Always read them, especially this one about recycling.

Recycling, position by position

The second sum from before, c(1, 2, 3) + c(10, 20), unfolded. The long vector sets the positions and the short one keeps repeating underneath:

PositionLong c(1, 2, 3)Short, recycledSumWhy
111011First value of the short one
222022Second value of the short one
331013The short one has run out and starts again. The 20 of this second round is left over, and that is why it warns

And now the really dangerous part: if the long length is a multiple of the short one, R recycles without warning. With the 8 marks:

marks <- c(4.5, 7, 8.25, 5, 6.5, 9, 3.75, 7.5)
marks - c(5, 6)   # 8 marks minus 2 values: does it warn?

Output:

[1] -0.50  1.00  3.25 -1.00  1.50  3.00 -1.25  1.50

8 is a multiple of 2, so c(5, 6) is repeated four times: 5 is subtracted from the marks in odd positions and 6 from the even ones (4.5 − 5 = −0.5; 7 − 6 = 1; 8.25 − 5 = 3.25…). No error and no warning, just a result that means nothing. The warning saves you when the lengths do not fit; when they do fit, your only defence is to check length() of both vectors first.

Check you’ve got it: what does c(1, 2, 3, 4, 5, 6) * c(1, 10, 100) give? Does it warn?

It does not warn: 6 is a multiple of 3, so the short one is repeated twice in full, 1 10 100 1 10 100. Multiplying position by position: 1 · 1 = 1, 2 · 10 = 20, 3 · 100 = 300, 4 · 1 = 4, 5 · 10 = 50 and 6 · 100 = 600. R prints [1] 1 20 300 4 50 600.

Functions you will use every day

With a data vector, these functions give you the basic summary of any descriptive statistics exercise:

sort(marks)
sum(marks)
mean(marks)
median(marks)
range(marks)
sd(marks)
summary(marks)

Output:

[1] 3.75 4.50 5.00 6.50 7.00 7.50 8.25 9.00
[1] 51.5
[1] 6.4375
[1] 6.75
[1] 3.75 9.00
[1] 1.864853
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  3.750   4.875   6.750   6.438   7.688   9.000 

Let us check the median by hand, which is the one that gets people tangled. With the marks sorted (3.75, 4.5, 5, 6.5, 7, 7.5, 8.25, 9) there are 8 values, an even number, so the median is the mean of the two central ones: (6.5 + 7) / 2 = 6.75. It matches.

summary() puts on one line the minimum, the first quartile (1st Qu.), the median, the mean, the third quartile and the maximum. It computes the quartiles with R’s default method, which sometimes does not match the one in your lecture notes: in ME1 you will see that quantile() has several methods and you have to choose the one your lecturer asks for.

Matrices: vectors with rows and columns

A matrix is a vector with two dimensions: rows and columns. You create it with matrix(), saying how many rows (or columns) you want:

How R fills a matrixThe numbers 1 to 6 in a 2-row matrix: by columns on the left, by rows with byrow = TRUE on the right.matrix(1:6, nrow = 2)by columns (the default)135246byrow = TRUE123456m[2, 3] → 6row first, then columnm[, 2] → 2 5blank = the whole row or column
The coral arrows show the filling order. The right-hand matrix is the one you would write by hand.
m <- matrix(1:6, nrow = 2)
m
matrix(1:6, nrow = 2, byrow = TRUE)
dim(m)

Output:

     [,1] [,2] [,3]
[1,]    1    3    5
[2,]    2    4    6
     [,1] [,2] [,3]
[1,]    1    2    3
[2,]    4    5    6
[1] 2 3

Look at the drawing and the output: by default, R fills by columns (1 and 2 in the first, 3 and 4 in the second…). If you want to fill by rows, as you would write on paper, add byrow = TRUE. dim(m) gives you the dimensions: 2 rows and 3 columns.

To take elements out, the brackets take two positions separated by a comma, first the row and then the column. If you leave one blank, you get the whole row or column:

m[2, 3]     # row 2, column 3
m[1, ]      # the whole of row 1
m[, 2]      # the whole of column 2
t(m)        # the transpose: rows become columns
m * 2       # each element times 2
m %*% t(m)  # matrix product (2x3 by 3x2 = 2x2)

Output:

[1] 6
[1] 1 3 5
[1] 3 4
     [,1] [,2]
[1,]    1    2
[2,]    3    4
[3,]    5    6
     [,1] [,2] [,3]
[1,]    2    6   10
[2,]    4    8   12
     [,1] [,2]
[1,]   35   44
[2,]   44   56

Careful with the last two: m * 2 multiplies each element, just like with vectors, but the algebra matrix product is written %*%. Let us check the first element of m %*% t(m): it is row 1 of m times column 1 of t(m), that is 1·1 + 3·3 + 5·5 = 1 + 9 + 25 = 35.

The matrix product, cell by cell

The check above only does the first cell. These are all four, always with the same rule: cell [i, j] is row i of the first matrix times column j of the second, multiplying element by element and adding up. Remember that m has rows 1 3 5 and 2 4 6, and that the columns of t(m) are those same rows stood upright.

CellRow of mColumn of t(m)CalculationResult
[1, 1]1 3 51 3 51 · 1 + 3 · 3 + 5 · 5 = 1 + 9 + 2535
[1, 2]1 3 52 4 61 · 2 + 3 · 4 + 5 · 6 = 2 + 12 + 3044
[2, 1]2 4 61 3 52 · 1 + 4 · 3 + 6 · 5 = 2 + 12 + 3044
[2, 2]2 4 62 4 62 · 2 + 4 · 4 + 6 · 6 = 4 + 16 + 3656

Now look at the dimensions. To be able to multiply, each row of the first matrix must have as many elements as each column of the second, because they are paired one by one. m is 2×3 and t(m) is 3×2: the inner 3s match, and the result keeps the outer ones, 2×2. If they do not match, as in m %*% m (2×3 times 2×3: rows of 3 against columns of 2), R stops with the error non-conformable arguments, «dimensions that do not fit».

Mixing up * and %*%. With *, R does no algebra: it multiplies cell by cell, and if both matrices have the same dimensions it never complains. If you expected a matrix product and you get a matrix the same size as the ones you started with, you wrote *.

Check you’ve got it: what are the dimensions of t(m) %*% m and what is its cell [1, 1]?

t(m) is 3×2 and m is 2×3: the inner ones (2 and 2) match, so it can be done, and the result is 3×3, the outer ones. Cell [1, 1] is row 1 of t(m), which is 1 2, times column 1 of m, which is also 1 2: 1 · 1 + 2 · 2 = 1 + 4 = 5. The order matters: m %*% t(m) was 2×2 and this one is 3×3.

A contingency table

In ME1, matrices show up mostly as frequency tables of two variables. For example, students who pass or fail in two groups:

results <- matrix(c(12, 8, 5, 15), nrow = 2,
                  dimnames = list(c("Pass", "Fail"), c("Group A", "Group B")))
results
rowSums(results)       # total of each row
colSums(results)       # total of each column
prop.table(results)    # each cell divided by the total (40)

Output:

     Group A Group B
Pass      12       5
Fail       8      15
Pass Fail 
  17   23 
Group A Group B 
     20      20 
     Group A Group B
Pass     0.3   0.125
Fail     0.2   0.375

dimnames names the rows and the columns (rows first). Since it fills by columns, group A has 12 passes and 8 fails, and group B, 5 and 15. rowSums and colSums give the marginal totals and prop.table divides each cell by the total of 40 students: 12 / 40 = 0.3. It is the first step of the relative frequency tables you will see in the descriptive statistics topic.

A proportion of which total?

That 0.125 in the «Pass, Group B» cell is very often misread. It does not say that 12.5 % of group B pass. It says that 12.5 % of the 40 students are in group B and have also passed. If the question is «what proportion passes within group B?», the total is no longer 40 but 20 (the students in B), and you have to ask prop.table for it with margin. The same cell, the 5 in «Pass, Group B», answers three different questions depending on the total you divide by:

QuestionTotal you divide byIn RResult
What share of all students passes and is in B?40, everyoneprop.table(results)5 / 40 = 0.125
What share of group B passes?20, column Bprop.table(results, margin = 2)5 / 20 = 0.25
What share of those who pass is in B?17, the Pass rowprop.table(results, margin = 1)5 / 17 = 0.29

margin = 1 divides by rows and margin = 2 by columns, in the same order as the brackets [row, column]. All three calculations are correct; what changes is the question. The second one shows what really matters: in group A 60 % pass and in group B, 25 %. It is the idea of conditional probability you will see in the probability topic.

Check you’ve got it: of the students who fail, what proportion is in group B? Which margin do you use?

«Of those who fail» fixes the Fail row, so the total is 8 + 15 = 23. Of them, 15 are in B: 15 / 23 = 0.65. Since you divide by the row total, it is prop.table(results, margin = 1), which gives 0.6521739 in that cell (0.65 to 2 decimals).

Typical mistakes

Besides the ones that have already come up, these three appear as soon as you start writing scripts:

Forgetting the c(). mean(4, 7, 9) gives 4, not 6.67, because mean only looks at its first argument; it takes the others as options. The right way is mean(c(4, 7, 9)).

Using a decimal comma. In R, 6,5 is not a number: inside c(6,5) they are two values, 6 and 5. Decimals are always written with a point: 6.5.

If a line is left «half done» and the console shows a + instead of >, R is waiting for you to close a bracket or some quotes. Close it or press Esc to start again.

Try it in the R playground

This program puts the article together in one complete calculation: the mean, the variance step by step and how many marks are passes. Copy it into the R playground (or into an RStudio script) and run it:

# My ME1 lab marks
marks <- c(4.5, 7, 8.25, 5, 6.5, 9, 3.75, 7.5)
average <- mean(marks)
deviations <- marks - average        # each mark minus the mean
squares <- deviations^2              # each deviation squared
variance <- sum(squares) / (length(marks) - 1)
passes <- marks[marks >= 5]          # the filter with the logical mask
cat("Mean:", average, "\n")
cat("Sum of deviations:", sum(deviations), "\n")
cat("Variance:", variance, " (var() gives", var(marks), ")\n")
cat("Passes:", length(passes), "out of", length(marks), "\n")

Output:

Mean: 6.4375 
Sum of deviations: 0 
Variance: 3.477679  (var() gives 3.477679 )
Passes: 6 out of 8 

cat() writes several things in a row on one line (the final "\n" is the line break). What to watch while you run it:

  1. Run it line by line with Ctrl + Enter (it works the same in the site’s playground and in RStudio) and open the Environment tab after the second line: marks appears as num [1:8], a numeric vector of 8 values.
  2. After the deviations line, notice that it also has 8 values. It has subtracted the mean from each mark without any loop.
  3. The sum of the deviations comes out as 0: those above the mean balance those below. It is a property of the mean you will see proved in class. (With other data you may get something like 1.776357e-15, a zero with rounding error.)
  4. Check that variance and var(marks) give the same, 3.477679.
  5. Change the 5 in marks >= 5 to a 7 and run it again: the number of passes drops to 4.

If you get something wrong, the playground marks the line and explains the error, which is very handy when you are starting.

Summary

ConceptIn RExample
Assign<-average <- mean(marks)
Vectorc(), :, seq(), rep()c(4.5, 7, 9)
Pick[ ], from 1marks[marks >= 5]
OperateElement by elementmarks - mean(marks)
Summarymean, median, var, sd, summarysummary(marks)
Matrixmatrix(), [row, column]m[2, 3]
Missing valueNA, na.rm = TRUEmean(x, na.rm = TRUE)

Three ideas to keep:

  1. In R everything is a vector and operations go element by element: you will hardly ever need a loop to do sums with data.
  2. Brackets filter. A condition in brackets (x[x > 5]) is the way to keep the data you care about.
  3. Read the warnings. A Warning message does not stop the program, but it is often the only clue that something is wrong.

In the second part, R from scratch (2), we move on to the structure you will work with in every lab: data frames, how to read a .csv, how to write your own functions and how to install and load packages.

Keep goingAll R articles

Did this article help you? Here is how you can support SergioLearns →