BeginnerLesson 1 of 155 min read

Your First R Session: Values, Vectors and Functions

Start with R as a calculator, create variables and vectors, meet the basic types, call functions, and compute a first mean that is checked in Python.

In this lesson you will

  • Run R code and read its output
  • Create variables and vectors
  • Know the basic types
  • Call functions such as mean and length

About 28 minutes

Nia wants to understand her plant experiment

Nia teaches science at a secondary school. Her class grew twelve bean plants for four weeks, four with no fertiliser, four with organic compost and four with a chemical fertiliser, and measured every plant’s height in centimetres. She wants to know whether the fertiliser made a difference, and she wants an analysis that she can repeat next year, not a spreadsheet that she edited by hand. R is a language made for exactly this work: it was designed by statisticians, it is free, and it is used in universities, hospitals, banks and newsrooms for data analysis and graphics.

You can type R code at the console and see the answer at once, or you can save it in a script file and run it with Rscript, which is what this course does. Everything in R is a value, and the basic building block is the vector, an ordered collection of values of one type. A single number is just a vector of length one. You assign with the arrow, <- , read as "gets", though = also works at the top level. You create a vector with the function c, which means combine, and you call a function by its name and parentheses. The four basic types are numeric for decimals, integer for whole numbers, written with an L, character for text and logical for TRUE and FALSE.

Type Example class() says
Decimal 12.5 numeric
Whole number 5L integer
Text “control” character
Logical TRUE logical
Missing NA logical (and special)
plants <- 12
weeks <- 4
cat("Nia grows", plants, "plants for", weeks, "weeks\n")

heights <- c(12.1, 13.4, 11.8, 12.9)
cat("control heights:", heights, "\n")
cat("count:", length(heights), " mean:", mean(heights), " max:", max(heights), "\n")
cat("types:", class(plants), class(5L), class("control"), class(TRUE), class(heights), "\n")

growth <- heights * 2.54 / 2.54 + 1
cat("each plant plus 1 cm:", growth, "\n")
cat("sum:", sum(heights), " range:", range(heights), " sd:", round(sd(heights), 4), "\n")
cat("sequence:", 1:5, "| seq by 0.5:", seq(0, 2, by = 0.5), "| rep:", rep(c("a", "b"), times = 2), "\n")
cat("integer division:", 7 %/% 2, " remainder:", 7 %% 2, " power:", 2^10, " sqrt:", sqrt(144), "\n")
cat("is 0.1 + 0.2 equal to 0.3?", 0.1 + 0.2 == 0.3, "| all.equal says", isTRUE(all.equal(0.1 + 0.2, 0.3)), "\n")
print(heights)
print(summary(heights))
Nia grows 12 plants for 4 weeks
control heights: 12.1 13.4 11.8 12.9
count: 4  mean: 12.55  max: 13.4
types: numeric integer character logical numeric
each plant plus 1 cm: 13.1 14.4 12.8 13.9
sum: 50.2  range: 11.8 13.4  sd: 0.7326
sequence: 1 2 3 4 5 | seq by 0.5: 0 0.5 1 1.5 2 | rep: a b a b
integer division: 3  remainder: 1  power: 1024  sqrt: 12
is 0.1 + 0.2 equal to 0.3? FALSE | all.equal says TRUE
[1] 12.1 13.4 11.8 12.9
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max.
  11.80   12.03   12.50   12.55   13.03   13.40

The script printed the number of plants and weeks, then worked on the four control heights 12.1 13.4 11.8 12.9. The count is 4, the mean is 12.55 and the maximum is 13.4. The function class showed the types of the five values as “numeric integer character logical numeric”: note that a plain 12 is numeric, not integer, and only 5L is an integer. Arithmetic on a vector is applied to every element at once, so heights plus 1 gave 13.1 14.4 12.8 13.9, with no loop needed, a feature called vectorisation that is central to R.

The other lines show the everyday helpers. The sum is 50.2, the range is the pair 11.8 13.4, and the standard deviation, rounded to four decimals, is 0.7326. The colon makes the sequence 1 2 3 4 5, seq with by gives 0 0.5 1 1.5 2, and rep repeats a vector, giving “a b a b”. The operators %/% and %% give the integer quotient 3 and the remainder 1, the caret is the power, so 2^10 is 1024, and the square root of 144 is 12. Finally, summary printed the five-number summary and the mean in one line, and print showed a vector with its index in square brackets.

A classic surprise: 0.1 + 0.2 == 0.3 is FALSE in R, as in every language that uses binary floating point, so compare decimals with all.equal, which allows a tiny tolerance and returned TRUE here, wrapped in isTRUE so that the result is always a single TRUE or FALSE.

Independent check: Python computed the same mean from the four numbers, statistics.mean gives 12.55, the sample standard deviation 0.7326 and the quartiles with numpy. They agree with R to the digits shown. Note that R’s sd is the sample standard deviation, dividing by n minus 1, the same as Python’s statistics.stdev.

Check by hand: 12.1 + 13.4 + 11.8 + 12.9 = 50.2, and 50.2 divided by 4 is 12.55. The median of four sorted values, 11.8, 12.1, 12.9 and 13.4, is the mean of the middle two, 12.5. 2 to the power 10 is 1,024, and 7 divided by 2 is 3 remainder 1.

R counts from 1

The first element of a vector is x[1], not x[0]. This is the most common surprise for people who know another language, and it comes back in the next lesson.

Use scripts, not only the console

Save your code in a .R file and run it with Rscript. A script is a record of exactly what you did, so you or a colleague can repeat the analysis on new data next year.

About this course

Every program in this lesson was run with R 4.3.3 using Rscript –vanilla (base R only, no packages) while the course was written. R releases new versions every year, so check r-project.org for the current version and for any change in behaviour.

Practice

Write a script with the heights of the organic group, 15.2, 16.8, 14.9 and 15.7. Print their count, mean and range, and check the mean on a calculator. Try 5L / 2L and class(5L / 2L), then 5L %/% 2L and its class.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does c(1, 2, 3) do?

  1. Prints a value
  2. Creates a vector
  3. Deletes a variable
  4. Loads a package

c means combine.

How do you assign in R?

  1. With <-
  2. With :=
  3. Only with let
  4. With ->> only

The arrow is the idiom; = also works at top level.

What is the index of the first element of a vector?

  1. 1
  2. 0
  3. -1
  4. It depends

R counts from 1.

Why is 0.1 + 0.2 == 0.3 FALSE?

  1. R has a bug
  2. Vectors are different
  3. Because of NA
  4. Binary floating point cannot store these decimals exactly

Use all.equal.

What is vectorisation?

  1. A kind of loop
  2. A plot type
  3. A package
  4. An operation applied to every element at once

heights + 1 changes every element.

Summary

  • R is a language for data analysis; scripts make analysis repeatable.
  • The vector is the basic building block; operations apply to every element.
  • The basic types are numeric, integer, character and logical.
  • R counts from 1; compare decimals with all.equal.

Next lesson

Lesson 2 covers indexing, recycling and missing values.

Questions

Is R hard to learn?

Many people find the first week easy, since R is excellent for quick answers, and the language has some odd corners that you meet gradually. This course covers the ones that matter.

Do I need RStudio?

No. It is a popular editor for R, and everything here runs with plain Rscript. Check posit.co for the current version if you want it.

What is the difference between R and Python?

Both are used for data analysis. R was built for statistics and has a huge collection of statistical methods, and Python is a general-purpose language with a strong data ecosystem. Many analysts know both.

Progress is saved in this browser.