Skip to main content

Section A.3 Elements of R grammar

R is a programming language, and as a language it has a number of elements that are basic to its understanding. In this section we discuss functions (the "verbs" in the R grammar) and objects (the "nouns" in the R grammar).

Subsection A.3.1 Functions

Functions do things. They are called by a certain name, usually a name which represents what they do, and they are followed by brackets (). Within the brackets, you can put whatever it is that you want the function to work with. For example, the code we wrote in previously was the print() function. This function told R to print into the console whatever we put in the brackets ("Hello World!").
It is the same idea with a personalised greeting: if you want to print ’Hello Reka’, you will need to have "Hello Reka" inside the brackets:
print("Hello Reka")
## [1] "Hello Reka"
There are so many functions in R. We will be learning many of them throughout the book. Print is fun, but most of the time, we will be using functions to help us with our data analysis. For example, getting the minimum, maximum, or mean of a list of numbers. R does this using functions in a very similar way.
For example, if we have a bunch of numbers, we just find the appropriate function to get the summary we want:
mean(c(10, 34, 5, 3, 77))
min(c(10, 34, 5, 3, 77))
max(c(10, 34, 5, 3, 77))
## [1] 25.8
## [1] 3
## [1] 77
How can you find the function you need? Throughout this book, you will learn a list that appears at the top of each lesson. A recommendation when you are starting with R is to also create a ’function cookbook’, where you write down a list of functions, what the functions do, and some examples. Here is an example:
A screen capture of the Google Documents web app, with a file titled ’My R Function Cookbook’ open. The document contains a table with three columns, labeled ’Function’, ’What it does’, and ’An example’. The first three rows are visible, with entries for the functions ’print’, ’mean’, and ’min’, along with their descriptions and an example usage.
Figure A.3.1. An example of an R function cookbook
You can use Google to make your cookbook; and the website stackoverflow, in particular, can help you find the function you need. But be wary, especially in the beginning, that you understand what the function does. There can be several different functions for the same action.
NOTE: R is case-sensitive! For example:
# Calculating the logarithm
Log(100)

# ERROR!
# Instead, it should be:
log(100)
## [1] 4.60517
So make sure that you are specific about upper and lower case letters in your collection of relevant functions. In general, almost all functions will start with lower case letter. One exception is the View() function.

Subsection A.3.2 Objects

You can think of objects as boxes where you put things. Imagine a big, empty cardboard box. We can create this big empty box in R by simply giving it a name. Usually, you want your object/box to have a good descriptive name, which will tell people what is in it. Imagine moving house. If you have a cardboard box full of plates, you might want to label it "plates". That way, when carrying, you know to be careful, and when unpacking, you know its contents will go in the kitchen. On the other hand, if you named it "box1", then this is a lot less helpful when it comes to unpacking.

Subsubsection A.3.2.1 Creating an object

Let us create an object called ’plates’. To do this, you go to your script, and type ’plates’.
But if you run this code, you will get an error. Try it and you will see the error ’Error! Object plates not found’. This is because you have not yet put anything inside the plates ’box’. Remember objects are like boxes, so there must be something inside our object ’plates’. In order for this object to exist, you have to put something inside it, or in R-speak assign it some value.
Therefore, we make an object by using an assignment operator ( <- ). In other words, we assign something to an object (i.e., put something in the box). For example:
plates <- "yellow plate"
Now if we run this, we will see no error message, but instead, we will see the plates object appear in our environment pane.
Here are some more examples to illustrate:
# Putting '10' in the 'a' box
a <- 10

# Putting 'Hello!' in the 'abc123' box
abc123 <- "Hello!"
In these examples, we are putting the value of 10 into the object a, and the value of ’Hello!’ into the object abc123.
Earlier, we introduced you to the Environment and History pane. We mentioned that it lists objects you defined. After making the ’a’ and ’abc123’ objects, they should appear in that pane under the Environment tab.

Subsubsection A.3.2.2 Types of objects

Why are objects important? We will be storing everything in our data analysis process in these objects. Depending on what is inside them, they can become a different type of object. Here are some examples:
Data structures are important objects that store your data, and there are five main types but we focus on three for this course:
  1. (atomic) vector: an ordered set of elements that are of the same class. Vectors are a basic data structure in R. Below are five different classes of vectors:
    # 1. numeric vector with three elements
    my_1st_vector <- c(0.5, 8.9, 0.6)
    
    # 2. integer vector with addition of L at the end of the value
    my_2nd_vector <- c(1L, 2L, 3L)
    
    # 3. logical vector
    my_3rd_vector <- c(TRUE, FALSE, FALSE)
    # 'my_4th_vector' creates a logical vector using abbreviations of True and False,
    #   but you should use the full words instead
    my_4th_vector <- c(T, F)
    
    # 4. character vector
    my_5th_vector <- c("a", "b", "c")
    
    # 5. complex vector (we will not use this for our class)
    my_6th_vector <- c(1+0i, 2+4i)
    
  2. lists: technically they, too, are vectors but they are more complex because they are not restricted on the length, structure, or class of the included elements. For example, to create a list containing strings, numbers, vectors and a logical, use the list() function, and inside the brackets, put everything you want to combine into a list:
    list_data <- list("teal", "sky blue", c(10, 5, 10), TRUE, 68.26, 95.46, 99.7)
    
    Above, we created list_data, an object that contains all those things that we put inside the list() function. This function serves to create a list from combining everything that is put inside its brackets.
    Use the class() function to confirm that the objects have been defined as a list:
    class(list_data)
    
  3. data frames: also store elements but differ from lists because they are defined by their number of columns and rows; the vectors (columns) must be of the same length. Data frames can contain different classes, but each column must be of the same class. For example, if you want to combine some related vectors to make a data frame on violent American cities, use the function data.frame():
    # Making some relevant vectors
    TopVioCities <- c("St. Louis", "Detroit", "Baltimore") # some violent US cities
    VioRatePer1k = c(20.8, 20.6, 20.3) # their violence rates per 1,000 persons
    State <- c("Missouri", "Michigan", "Maryland") # in what states are these cities found
    
    # Join them to make a data frame called 'df'
    df <- data.frame(TopVioCities, VioRatePer1k, State)
    
    We can then view the data frame, ’df’, with the View() function:
    View(df)
    

Subsubsection A.3.2.3 Doing things to objects

We have learned what functions are (i.e., things that do things) and what are objects (i.e., the boxes that hold things). We also saw some functions which helped us create objects. Functions can also do things to objects. For example, we saw the function class() that told us about what kind of object list_data was, and View() which allowed us to have a look at our dataframe we called df.
Let us look back at our plates object. Remember, it was the object that held our kitchen items. We added ’yellow plate’ to it. Now let us add some more items and let us use the concatenate c() function for this again:
plates <- c("yellow plate", "purple plate", "silver plate", "orange bowl")
Let us say that we suddenly forgot what was in our object called ’plates’. Like what we learned earlier, we use the function print() to see what is inside this object:
print(plates)
## [1] "yellow plate" "purple plate" "silver plate" "orange bowl"
This can apply to obtaining the mean, minimum, and maximum. You could assign those statistics to an object this time:
nums <- c(10, 34, 5, 3, 77)
Now if we want to know the mean, we can take the mean of the object nums, which we just created:
mean(nums)
## [1] 25.8
The object we will use most frequently though is data frames. These hold your data in a format whereby each column represents a variable, and each row an observation.
Just earlier, we had created a dataframe called df previously. If you have not yet copied this over into your own RStudio, do this now. You should have the object df in your environment. When you run View(df), you should see this dataset:
A screen capture of the RStudio desktop app. Some work is present in the four panes, with two areas of importance circled in orange, with arrows drawn pointing towards them. The top left pane is circled, and has the tab ’df’ open, which shows a table of the contents of the dataframe, with columns labeled ’TopVioCities’, ’VioRatePer1k’, and ’State’, and numbered columns. The top right frame with the ’Environment’ tab has an entry circled under the ’Data’ heading. The entry is labeled ’df’, and is described as ’three obs of three variables’.
Figure A.3.2. View your dataframes
To do something to an entire dataframe, we would use the name of the object (df) to refer to it. In the case of the View() function, we want to see the whole thing, so we will call View(df). On the other hand, if we want to refer to only one variable in the data, (remember back to term 1 - each variable is held in each column) there is a special notation to do this.
To refer to a variable (column) inside a dataframe, you use:
\(\text{dataframe name} + \$ + \text{variable name}\)
For example, to refer to the variable VioRatePer1k, we use the notation df$VioRatePer1k.
And if we wanted to View only that column, we use:
View(df$VioRatePer1k)
You should see one column of the dataframe appear in the top left pane.
Say, we wanted to know the mean violence rate across our units of analysis, the cities, for example, we would take the numeric column to calculate this:
mean(df$VioRatePer1k)
## [1] 20.56667