# Getting started

## Using R as a calculator

The simplest thing you could do with R is do arithmetic:

Here, we’ve added 1 and and 100 together to make 101. The [1] preceeding this we will explain in a minute. For now, think of it as something that indicates output.

Order of operations is same as in maths class (from highest to lowest precedence)

• Brackets
• Exponents
• Divide
• Multiply
• Subtract

What will this evaluate to?

The “caret” symbol (or “hat”) is the exponent (to-the-power-of) operator (read x ^ y as “x to the power of y”). What will this evaluate to?

Use brackets (actually parentheses) to group to force the order of evaluation if it differs from the default, or to set your own order.

But this can get unweidly when not needed:

See ?Arithmetic for more information, and two more operators (you can also get there by ?"+" (note the quotes)

If R thinks that the statement is incomplete, it will change the prompt from > to + indicating that it is expecting more input. This is not an addition sign! Press “Esc” if you want to cancel this statement and return to the prompt.

The usual sort of comparison operators are available:

See ?Comparison for more information (you can also get there by help("==").

Really small numbers get a scientific notation:

which you can write in too:

Read e-XX as “multiplied by 10^XX”, so 2e-4 is 2 * 10^(-4).

## Mathematical functions

R has many built in mathematical functions that will work as you would expect:

Plus things like probability density functions for many common distributions, and other mathematical functions (e.g., Gamma, Beta, Bessel). If you need it, it’s probably there.

## Variables and assignment

You can assign values to variables using the assignment operator <-, like this:

And now the variable x contains the value 0.025:

(note that it does not contain the fraction 1/40, it contains a decimal approximation of this fraction. This appears exact in this case, but it is not. These decimal approximations are called “floating point numbers” and at some point you will probably end up having to learn more about them than you’d like).

Look up at the top right pane of RStudio, and you’ll see that this has appeared in the “Workspace” pane.

Our variable x can be used in place of a number in any calculation that expects a number.

The right hand side of the assignment can be any valid R expression.

It is also possible to use the = operator for assignment:

…but this is much less common among R users. The most important thing is to be consistent with the operator you use. There are occasionally places where it is less confusing to use <- than =, and it is the most common symbol used in the community. So I’d recommend <-.

Notice that assignment does not print a value.

Notice also that variables can be reassigned (x used to contain the value 0.025 and and now it has the value 100).

Assignment values can contain the variable being assigned to: What will x contain after running this?

The right hand side is fully evaluated before the assignment occurs.

Variable names can contain letters, numbers, underscores and periods. The cannot start with a number. They cannot contain spaces at all. Different people use different conventions for long varaible names, these include

• periods.between.words
• underscores_between_words
• camelCaseToSeparateWords

What you use is up to you, but be consistent.

### Exercise:

Compute the difference in years between now and the year that you started at Macquarie University. Divide this by the difference between now and the year when you were born. Multiply this by 100 to get the percentage of your life spent at university. Use parentheses if you need them, use assignment if you need it.

This problem is as much about thinking about formalising the ingredients of a problem as much as actually getting the syntax correct.

## Vectors

R was designed for people who do data analysis. There is a reason why “data” is a more common term than “datum” – generally you have more than one piece of data (although the Guardian argues that this distinction is old fashioned). As a result in R all data types are actually vectors. So the number ‘1’ is actually a vector of numbers that happens to be of length 1.

To build a vector, use the c function (c stands for “concatenate”).

We have assigned this vector to the variable x.

(notice how RStudio has updated its description of x. If you click it, you’ll get an option to alter it, which is rarely what you want to do).

This is a deep piece of engineering in the design; most of R thinks quite happily in terms of vectors. If you wanted to double all the values in the vector, just multiply it by 2:

You can get the maximum value…

…minimum value…

…sum…

…mean value…

…and so on. There are huge numbers of functions that operate on vectors. It is more common that functions will than that they won’t.

Vectors can be summed together:

And they can be concatenated together:

and scalars can be added to them

Be careful though: if you add/multiply together vectors that are of different lengths, but the lengths factor, R will silently “recycle” the length of the shorter one:

(note how the first and third element have been multiplied by -2 while the second and fourth element are multiplied by 2).

If the lengths to not factor (i.e., the length of the shorter vector is not a factor of the length of the longer vector) you will get a warning, but the calculation will happen anyway:

This is almost never what you want. Pay attention to warnings. Note that Warnings are different to Errors. We just saw a warning, where what happened is (probably) undesirable but not fatal. You’ll get Errors where what happened has been deemed unrecoverable. For example

Just as with the scalars, as well as doing arithemetic operators we can do comparisons. This returns a new vector of TRUE and FALSE indicating which elements are less than 10:

You can do vector-vector comparisons too:

And combined arithmetic operations with comparison operations. Both sides of the expression are fully evaluated before the comparison takes place.

Be careful with comparisons: This compares the first element with -20, the second with 20, the third with -20 and the fourth with 20.

This does nothing sensible, really, and warns you again:

All the comparison operators work in fairly predictible ways:

Sequences are easy to make, and often useful. Integer sequences can be made with the colon operator:

Which also works backwards

Step in different sizes

Now we will see the meaning of the [1] term – this indicates that you’re looking at the first element of a vector. If you make a really long vector, you’ll see new numbers:

## Exercise:

One thing you can do with sequences is you can very informally look at convergent sequences. For example, the sum of squares of the reciprocals of integers:

1. What is the sum of the first four squares?
2. What is the sum of the first 100?
3. …of the first 10,000?
4. if $x$ is the answer to 3, what is the square root of $6x$?

### A possible solution

1.

2.

3.

4.

Back to main page