Chapter 3 R Scripts
Now that you are hopefully familiar with the console, lets try out writing in a script! R
will continue to provide the output in the console, and hitting enter won’t make R
run any command. You now need to press Ctrl + Enter (Cmd + Enter).
R
operates on named data structures, and you can create very simple to very complex structures.
# In your script, create an object a and assign it the value of 1
a <- 1
# In the above, we would say "the variable (object) a is assigned to 1", or "a gets 1"
# increment a by 1
a + 1
## [1] 2
# OK, now see what the value of a is
a
## [1] 1
So, R
returned us output as if it forgot we asked it to do a + 1
and didn’t change its value. That’s because we weren’t clear in what we wanted! The only way to keep this new value is to put it in an object.
b <- a + 1
# now let's see
b
## [1] 2
# success!
Quick Note: The <-
operator is used to ‘point’ to the object receiving the stated value. In most cases =
can be used instead. You can also make assignments in the other direction too:
b + 1 -> c
c
## [1] 3
Now, lets create a vector (or string) of numbers. This is a single entity that consists of a list of ordered numbers. If we wanted to create a vector called x, containing five numbers (2, 4, 6, 8, 10), we would use the R command:
x <- c(2, 4, 6, 8, 10)
In simple words, we have now created a list of the five numbers, and assigned them to the object x
. We made use of the c() function, as we were giving R a list of values. Let’s take a look at x
.
x
## [1] 2 4 6 8 10
You can now use these objects in other commands. For example, lets say you wanted to square each of the values in x
, or multiply by b
:
x^2
## [1] 4 16 36 64 100
x*b
## [1] 4 8 12 16 20
3.1 Short Example
Now that you’ve created your first variables to store some numbers, lets try an example. Say that you have all found this book extremely helpful as an introduction to R
, and that you wanted to buy it. Firstly, I’d want to calculate how many copies I’d sell. Since there are (roughly) 40 students in this class, and you all loved it, I’m going to assume 40 sales, and create a variable called sales
. So, how do I do this?
sales <- 40
Now to work out how much money I’m going to make per book. I need to create another variable called royalty
, which we will use to indicate how much money I will get per copy sold. Let’s say I get £5 per copy.
royalty <- 5
The last thing I want to do is calculate how much money I’ll make from sales in this class. We now need to create our revenue
variable, and ask R
to print out the total value of revenue.
revenue <- sales * royalty
revenue
## [1] 200
And there we have it - £200. As far as R
thinks, the sales*royalty
is the exact same as 40*5
. What if at last minute a student decides to buy 10 copies for their friends too? That would mean that we need to update our revenue. The easiest way to do this is to overwrite the value.
revenue <- revenue + 50
revenue
## [1] 250