Primer 1 · Objects, functions and vectors
R in your browser, nothing to install
This page runs R inside your browser. It needs about 17 MB on first load (the R engine plus the machinery that runs and marks your code) and a minute or two on a slow connection. If nothing happens after that, your network is probably blocking it. Work through the R primer in RStudio instead. Everything taught here is taught there too.
There is no Stop button. If you write a loop that never ends, reload the page.
Three ideas carry the whole of Day 1: R stores things in objects, you do things with functions, and the commonest object is a vector. Run the cells, change the numbers, break them on purpose. For the full explanation of any of this, see the R primer.
Objects
<- is the assignment arrow. It puts the thing on its right into the name on its left.
Change 240 to your own department’s intake and run it again.
Functions
A function is a verb. It takes arguments in brackets, separated by commas.
Named arguments like digits = 2 are clearer than positional ones. Prefer them.
Vectors
c() combines values into a vector: a column of values, all of the same type. It is the most-used function in R.
A comparison returns a logical vector, one TRUE or FALSE per element:
A vector holds one type. Mix them and everything is silently converted to the most permissive type, a classic source of confusion:
Those quotation marks mean all three are now text. You cannot take the mean of that.
Time: 5 minutes
Five students sat an OSCE station and scored 78, 70, 91, 55 and 83. Put those marks into a vector called osce.
osce <- c(78, 70, 91, 55, 83)
osce <- c(78, 70, 91, 55, 83)c() combines values. The marks go inside the brackets, separated by commas.
Time: 5 minutes
How many of those five marks are 70 or above? A comparison gives you TRUE and FALSE, and sum() counts TRUE as 1.
osce <- c(78, 70, 91, 55, 83)
sum(osce >= 70)
osce <- c(78, 70, 91, 55, 83)
sum(osce >= 70)You do not need a loop. osce >= 70 compares every element at once.
Check yourself
Take Check yourself · Primer 1 on the Moodle course. Four questions, unlimited attempts, no marks. Every answer comes back with an explanation, so a wrong one costs you nothing and teaches you something.
Next
→ Primer 2 · Tibbles: put those vectors side by side into the rectangle you will actually analyse.