First Steps with R


What is this page?

This page is a living document. The idea is that it will evolve as I get questions on the basic functions in R, and I can add new sections whenever it would be helpful. The way to get the most out of this page is to code along with it. Make it so your machine gives the same output as is written here.

First things first - run your first programme

The first thing you will want to do with R is run some code. Writing your first programme is relatively easy. In this case, let’s try:

1 + 1
## [1] 2

If you type this into the source editor on the top left, and then run it by either highlighting it and clicking “Run” or by pressing Ctrl + Enter (or Cmd + Enter on Macs), you will see the output on the console at the bottom left.

first_code

Using functions

For our next programme we will use a function. Functions in R precede brackets and tell the computer to perform some task, like this one here:

print("hello world")
## [1] "hello world"

In this case the function print() is being performed on the string “hello world”. Which means it is printed to the console.

A slightly more complicated example could be printing a longer sentence, maybe with a few numbers in.

cat("This is", 1, "of the first things to do in R")
## This is 1 of the first things to do in R

In this case, the code tells the computer to concatenate (link together) the three different objects within the function, and then print them to the console together. The cat() function is useful when you have an object that changes which we will come back to later.

Saving objects

Let’s first look at what it means to save an object.

x <- "Cow"
print(x)
## [1] "Cow"

The arrow r <- is used to save whatever is on the right of it with the name of whatever is on the left of it. In this case, I have saved the word Cow to the letter x. Then when I print x (without any speech marks) it prints the word Cow.

If we overwrite x with a new object then R will print the new object.

x <- "Chicken"
print(x)
## [1] "Chicken"

And if we want to prove that everything is working, we can save two objects and then print them together.

x <- "Chicken"
y <- "Cow"
cat(x, "is a bird, whereas a", y, "is not")
## Chicken is a bird, whereas a Cow is not

So far so good. This is all very entertaining, but it isn’t exactly helpful.

This is where saving vectors comes in. You can save an object that has more than one item inside it.

For example:

x <- c(1,2,3,4,5)
print(x)
## [1] 1 2 3 4 5

This saves the numbers 1,2,3,4,5 as a vector. A vector is a type of data structure in R which is essentially a sequence of items which are all the same type. In this case, they are all numbers. The little c at the start of the list tells R you are making a vector - you have to use this every time you want to save a vector. You can perform functions on a saved vector like this.

print(x*2)
## [1]  2  4  6  8 10
print(x^2)
## [1]  1  4  9 16 25
print(mean(x))
## [1] 3
Next