R as a calculator
We'll assume you have started an R prompt - if not go and start one now.
First steps
Let's try out R by trying a few interactive commands. First, can R add numbers together?
> 5 + 10
[1] 15
It can! It can also subtract them (-), multiply them (*), divide them (/), or exponentiate them (^).
Start by playing around with these arithmetic operations now to make sure you know what they are doing.
For example, what's to the power of ? Try
> 5^10
to find out.
R can also manipulate other things, like strings. Let's try a string now:
> "This is a string"
Strings can also be given using single quotes, as in 'This is also a string'.
However, you can't add two strings together - try it:
> "This is a string" + " as well"
Error in "This is a string" + " as well" :
non-numeric argument to binary operator
This illustrates that if you get something wrong R will try to tell you what it is. Here it's telling us that the
'binary operator' (which is +) expects 'numeric arguments' (i.e. numbers), as opposed to the strings we gave it.
That doesn't mean you can't concatenate strings - you can. In R, operations on strings use particular functions. The
one we want here is paste():
> paste( "This is a string", "as well" )
[1] This is a string as well.
Why 'paste'? Good question. This illustrates one of the worst aspects of R - some of the built-in functions have fairly cryptic names. Later on we'll suggest some useful libraries that make this easier.