Progress Log 103 (R): The True Basics
I’m taking an edX course entitled “Introduction to R for Data Science” and all of the concepts described below come from that course.
- Basic Arithmetic. We can calculate the sum of 1 and 2 by simply typing 1 + 2 in the console and hitting enter.
1 + 2
- Text: We can type text in the console by using double quotes and then hitting enter.
"Hi there, console!"
- A variable allows you to store a value or an object in R. You can use this variable’s name to easily access the value or the object that is stored within this variable.
- Creating variables: You use the less than followed by a dash to create a variable.
- Assigning variables: Suppose the number 2 is the height of a rectangle and 4 is the width. Let’s assign this value 2 to the variable ‘height’ and 4 to the variable of ‘width’.
height <- 2
width <- 4
- As you’re assigning variables in the R console, you’re actually accumulating an R workspace. It’s the place where variables and information are stored in R.
- Accessing objects in the workspace: You use the function ls() to show you a list of variables you have created in the R session.
- If we try to print out a non-exiting variable, for example, depth. R throws an error.
- The principle of accumulating a workspace through variable assignment makes these variables available for further use. Suppose we want to find out the area of our imaginary rectangle, we can calculate the area as follows:
height * width
- The result is 8 as you would expect. We can take this one step further and also assign the result of this calculation to a new variable, area.
area <- height * width
- If you now type area, you’ll see that it contains 8 as well.
- Inspecting the workspace again with
ls, you can see that the workspace contains three objects now: area, height, and width.
- An R script is a text file containing a collection of successive lines of R code that solve a particular task. When using R, you will build a lot of scripts to make things easier for you, and hopefully automate parts of your work.
- To comment, you start with the pound sign
#followed by the comment.
Cleaning up your workspace
rm()to remove variables from your workspace.
In its most basic form R can be used as a simple calculator. Consider the following arithmetic operators:
The last two might need some explaining:
- The ^ operator raises the number to its left to the power of the number to its right: for example, 3^2 equals 9.
- The modulo returns the remainder of the division of the number to the left by the number on its right, for example, 5 modulo 3 or
5 %% 3equals 2.