Learning outcomes–students will:

Prepartion and how to proceed

Before starting this tutorial you should have watched the video Introduction to RStudio.

In this tutorial we’ll use the command line in the Console window. You may be tempted to copy and paste from the tutorial to the command line. You can do this, but you’re advised not to as you will learn better by typing in the commands, which forces you to think more about what you are doing.

Variables and Variable Assignment

A variable is a name that holds (or represents) a value. We can assign values to variables and then use the variables in further operations. In object-oriented programming, a variable is considered an object. Type in the following code in your console window.

# example of variable assignment
x <- 10
y <- 5

Now type the following, then hit the Enter key.

# example of a addition operation 
x+y

Notice output from the operation is indicated with brackets. The number within the brackets indicates which element of the output is being displayed. For simple examples such as this it will be [1].

From here on, I’ll usually show you what is returned to the console, but you are highly encouraged to enter in the code and see what it does for yourself.

# example of variable assignment
x <- 10
y <- 5
x+y
## [1] 15

There are a few things you should have noticed. By typing # before a line of code we are indicating that this line is a comment–that is, it isn’t to be interpreted by the computer. Comments are very helpful to make our code intelligible to us humans, so commenting is a sensible idea and you’re highly encouraged to get in the habit of commenting your code! The other thing to notice is that the number of spaces on either side of the assignment symbol (<-) doesn’t matter, but some people find it helpful to be consistent and use one space for clarity.

Assignment of values to variables is dynamic. This means the computer holds the value of a variable in memory until it is assigned another value. We can also assign the output of an operation to a variable.

# example where y is now assigned the value of 20
x <- 10
y <- 20
# assign the addition of values in variables x and y to z
z <- x+y
# print output of variable z to the console
z
## [1] 30

Functions and Data Types

A function can be thought of as a small program (or tool) that takes something as input and returns something as output. Input for a function is placed within parentheses after the function name. Output by default will be returned to the console, but you can also assign output to a variable (which is often a good idea).

Variables can be of different data types. For example, a variable may be of the data type character (text or string), integer (whole number), double (number with decimals), or logical (TRUE/FALSE).

When doing analysis we may be working with a function that requires a particular data type as input that will not work if the input is of the incorrect data type. It’s therefore helpful to used code to find out the data type for a variable.

# Assign a text value to a variable
city <- "Corvallis"
# test data type with the is.integer() function
is.integer(city)
## [1] FALSE
# test the data type again with the is.character() function
is.character(city)
## [1] TRUE

The preceding example was fairly obvious and simple–we used code to confirm the variable ‘city’ is character and not integer. When coding we’re more likely to encounter problems like this–we think we’ve assigned the variable as an integer, but R recognizes it as double.

# assign a numeric value to a variable for temperature
temp <- 85
# test with is.integer() function
is.integer(temp)
## [1] FALSE
# test with is.double() function
is.double(temp)
## [1] TRUE

So, we found that the variable is holding a double data type and not an integer data type. Fortunately R has a function that allows us to convert, or coerce, one data type to another. Below, we’re going to assign the value for temp to a new variable using the as.integer() function to convert it to an integer data type. After running this code, there are two variables in memory: temp (which is double) and temp_int (which is integer).

# use as.integer() to convert variable temp to an integer data type
temp_int <- as.integer(temp)
# test (confirm) with is.integer() function
is.integer(temp_int)
## [1] TRUE

Data Classes

Data classes are data structures that are populated with data types. In this section we will learn about three data classes: vectors, matrices, and dataframes.

A vector is a one-dimensional variable of a given length. An easy way to create a vector is with the c() function (c is for combine).

# create a vector of temperatures
temp_vect <- c(50, 75, 85)
# look at the vector of temperatures
temp_vect
## [1] 50 75 85
# test with the is.vector() function to confirm it's a vector data class
is.vector(temp_vect)
## [1] TRUE

Sometimes its useful to create an empty vector of a given type and length which will be populated later. This can be done with the vector() function.

# create an empty vector of integers with length of 3
temp_vect_empty <- vector(mode="integer", length=3)
# look at the vector
temp_vect_empty
## [1] 0 0 0

A matrix is a two dimensional ‘rectangular’ structure defined by number of columns and rows.

# create a matrix of 2 columns x 2 rows; don't populate with numbers
matrix(ncol = 2, nrow = 2)
##      [,1] [,2]
## [1,]   NA   NA
## [2,]   NA   NA
# create a matrix populated with numbers from 1 to 6
matrix(1:6)
##      [,1]
## [1,]    1
## [2,]    2
## [3,]    3
## [4,]    4
## [5,]    5
## [6,]    6
# create a matrix populated with numbers from 1 to 6; specify two columns
matrix(1:6, ncol=2)
##      [,1] [,2]
## [1,]    1    4
## [2,]    2    5
## [3,]    3    6

The following code creates a 3x3 matrix and populates it with data. In this example the matrix() function is taking three arguments as input, each separated by a comma. The first argument is a vector of numbers created with the c() function, the next parameter specifies the dimensions of the matrix with a vector of the numbers 3 and 3, and the final argument specifies that the matrix will be filled one row at a time. After the matrix is created, column and row names are added. Finally the matrix is displayed to the console.

# create the matrix populated with values
city_temps <- matrix(c(60,90,45,85,110,60,70,100,50), c(3,3), byrow=TRUE)
# add column and row names to the matrix city_temps
colnames(city_temps) <- c("Corvallis", "Tucson", "Fairbanks")
rownames(city_temps) <- c("Morning", "Noon", "Evening")
# look at the matrix
city_temps
##         Corvallis Tucson Fairbanks
## Morning        60     90        45
## Noon           85    110        60
## Evening        70    100        50

We can now use a R function to calculate summary statistics from the matrix. Here we use the apply() function. The first argument is for the matrix, the second specifies whether to apply the statistical calculation to columns or rows (2 means columns), and the third specifies the statistic to calculate (in this example, the average as the mean).

# calculate the average temperature by city
ave_tmp_city <- apply(city_temps, 2, mean)
ave_tmp_city
## Corvallis    Tucson Fairbanks 
##  71.66667 100.00000  51.66667
# calculate average temperature by time of day
ave_tmp_day <- apply(city_temps, 1, mean)
ave_tmp_day
##  Morning     Noon  Evening 
## 65.00000 85.00000 73.33333

A matrix data structure can only contain data of a single type. If we want a rectangular data structure that allows multiple data types (e.g., integer, double, character) we use the dataframe. We can create a dataframe by binding vectors as columns of different data types using cbind() (meaning column bind) nested within the data.frame() function.

# create a vector of ave rainfall for three cities (Tucson, Corvallis,Fairbanks)
rain <- c(11.92,42.76,10.83)
# create a vector of ave temperature for three cities (Tucson, Corvallis,Fairbanks)
temp <- c(71, 53,28)
# create a vector of a comment for three cities (Tucson, Corvallis, Fairbanks)
comment <- c( "too dry", "just right","too cold")
# bind together the vectors and send output to a data frame
clim3_df <- data.frame(cbind(rain,temp,comment))
# add row names
rownames(clim3_df) <- c("Tucson", "Corvallis","Fairbanks")
# take a look at the dataframe
clim3_df
##            rain temp    comment
## Tucson    11.92   71    too dry
## Corvallis 42.76   53 just right
## Fairbanks 10.83   28   too cold

Reading and Writing Data

We’ve learned about variables, data types, and data classes–the basic building blocks for coding in R. Understanding how to create vectors, matrices and dataframes programatically is useful and good to know. Often however, we’ll work with data that are already created for us. For this we need to learn how to read data into R.

A common file format for reading in data is the .csv (comma separated values) file. If it’s not already set, set your Working Directory to the Lab1 folder. From the Session Menu choose Set Working Directory and specify your Lab1 folder.

# read in the .csv data assigning it to the variable clim_dat
clim4_df <- read.csv (file = "ClimateData.csv")
# look at clm_data
clim4_df
##          city  rain temp    comment
## 1      Tucson 11.92   71    too dry
## 2   Corvallis 42.76   53 just right
## 3   Fairbanks 10.80   28   too cold
## 4 New Orleans 62.45   78    too wet
# find out if it's a dataframe 
is.data.frame(clim4_df)
## [1] TRUE

The read.csv() function is just one of several ways to read data into R. Now is a good time to introduce you R’s Help. In the Plots/Files window (bottom right of RStudio) click on the Help tab and in the search utility (far right with magnifying class) search for ‘read.csv’. Take some time to familiarize yourself with the help for this function. What would you do if the first line of the table you’re reading in doesn’t have column names (i.e., headers)?

Sometimes you may want to save a vector, matrix, or dataframe to disk as a file. This can be done with the write.csv() function. Search R’s Help to find the basic arguments for this function (notice not all arguments are needed; in this case it will be just the first two).

Basic Plots

Visualizing data through plots is an important aspect of coding. The base plot() function in R allows us to create basic plots (a base function means it doesn’t require installing another package–more on that to come). In addition to the R Help, there are many useful resources on the internet to learn about R functions. One you might find useful is https://www.learnbyexample.org/r-plot-function/. From this page we can learn about how to make a basic plot and customize it (you’re encouraged to look at the page yourself, but I’ll explain).

# plot rainfall on x and temp on y axis, specify the symbol to 19, with red color
plot(clim4_df$rain, clim4_df$temp, pch=19, col="red")

# plot again, instead of defaults, give label names
plot (clim4_df$rain, clim4_df$temp, pch=19, col="red", xlab="Temperature (F)", ylab="Rainfall  (In)") 
# Add text above labels with city field
text(clim4_df$rain, clim4_df$temp, labels=clim4_df$city, cex=0.7, pos=3, col="blue")

# plot again, this time specify the x and y limits (ranges) 
plot (clim4_df$rain, clim4_df$temp, pch=19, col="red", xlab="Temperature (F)", ylab="Rainfall (In)", xlim=c(0,70), ylim=c(20,90), main="Rainfall and Temperature of Four Cities")
# Add text above labels with city field
text(clim4_df$rain, clim4_df$temp, labels=clim4_df$city, cex=0.7, pos=3, col="blue")

There are a few things you should notice from the above. First, there are several possible arguments to the plot() function and we don’t need to use all of them. The most important arguments are for the X and Y fields. These were specified by giving the dataframe name followed by $, followed by the name of the field in the dataframe. Another thing you should understand is the order in which you specify the arguments doesn’t matter, though usually the most important variables (usually required) are specified first, followed by others. To know what arguments are available, you really need to consult help, either through R’s Help or an online resource such as the one I suggested.

That’s it! You’ve learned about the basic building blocks of R, how to read and write data, and how to create simple plots. Well done! I encourage you to test your understanding by doing this week’s quiz and doing the challenge exercise!