R Programming – A Quick Introduction 2


1. Objective

In this R programming tutorial, we are going to learn what is R statistics, introduction to R, how to learn R as data analytics tool, various R software editors like RGui and R Studio and their components, how to develop R scripts, how to perform simple R operations in R and how to execute the developed scripts in R project with examples. We will also learn R introduction with Mathematical operations in R, R vectors and how to save the workspace in this R tutorial to learn R programming language.

R programming tutorial

2. Introduction to R Programming

R language is an open source program maintained by the R core-development team – team of volunteer developers from across the globe. R language used for performing statistical operations and is available from the R-Project website www.r-project.org. R is a command line driven program. The user enters commands at the prompt (> by default) and each command is executed one at a time.

Many routines have been written for R analytics by people all over the world and made freely available from the R project Website as packages. However, the basic installation (for Linux, Windows, or Mac) contains a powerful set of tools for most purposes.

R is a consolidated environment for performing statistical operations and generating R data analysis reports in graphical or text formats. R commands entered in the console are evaluated and executed. R cannot handle certain auto-formatting characters such as en-dashes or smart quotes; therefore, you need to be careful while copying and pasting commands into R from other applications.

a. Features of language R

  • It has effective data handling and storage facilities.
  • It supports a large pool of operators for performing operations on arrays and matrices.
  • It has facilities to print the reports for the analysis performed in the form of graphs either on-screen or on hardcopy.

You can obtain the installation files for the R program on the official R Website (www.r-project.org). The website has general documentation related to R along with the libraries of routines. The R program can be simply downloaded and installed from the R Website.

3. Working with R Scripts

R is utilized as a statistical programming environment for solving problems. R tools can also operate as a general matrix calculation toolbox.

R provides the freedom of selecting and editing tools to interact with the native console. While scripting in R, you don’t need to type commands but rather call functions to achieve results. The RConsole allows command editing.

The developed R scripts can be executed in the selected editor. You could download the data and save them in a local file, or just cut and paste the data from the browser to an editor such as Notepad, and then save them. The prominent editors available for R programming language are:

  • RGui (R graphical user interface)
  • Rstudio – Studio R offers a richer editing environment than RGui and makes some common tasks easier and more fun.

We will see about them in details below.

4. R Graphical User Interface (RGui)

Once you download R, RGui is provided as the standard graphical user interface (GUI). Most important component of RGui is the R console window. The console window in R is a place where instructions, scripts, and general R operations are performed. The console window also has R tools to manage the R environment. The R console screen appears every time the RGui is opened. It lists some basic information such as the R version installed and the licensing conditions.

In the RGui window you can open a new script, go to the ‘File’ menu and select ‘New Script’. The RGui can be accessed using the menu shortcuts created during the installation process.

The R prompt, a ‘>’ symbol indicates the place where the user can enter commands. To quit an active R session, you need to type the following code in the console after the command prompt (>):

> q()

R asks a question to ensure that the user wishes to quit the active session.

Note the parentheses after the q; this is because in R you don’t type commands but rather call functions to achieve results, even quit.

5. RStudio

RStudio is an integrated development environment (IDE) for R language. RStudio is a code editor and development environment, with some nice features that make code development in R easy and fun.

a. Features of RStudio

  • Code highlighting that gives different colors to keywords and variables, making it easier to read
  • Automatic bracket matching
  • Code completion, so as to reduce the effort of typing the commands in full
  • Easy access to R Help, with additional features for exploring functions and parameters of functions
  • Easy exploration of variables and values. RStudio is available free of charge for Linux, Windows, and Mac devices. It can be directly accessed by clicking the RStudio icon in the menu system on the desktop.

Because RStudio is available free of charge for Linux, Windows, and Mac devices, it is a good option to use with R. To open RStudio, click the RStudio icon in the menu system or on the desktop.

b. Components of RStudio

i. Source

Top left corner of the screen contains a text editor that lets the user work with source script files. Multiple lines of code can also be entered here. Users can save R script file to disk and perform other tasks on the script.

ii. Console

Bottom left corner is the R console window. The console in RStudio is identical to the console in RGui. All the interactive work of R programming is performed in this window.

iii. Workspace and History

The top right corner is the R workspace and history window. This provides an overview of the workspace, where the variables created in the session along with their values can be inspected. This is also the area where the user can see a history of the commands issued in R.

iv. Files, Plots, Package, and Help

The bottom right corner gives access to the following tools:

R Files: This is where the user can browse folders and files on a computer.

R Plots: This is where R displays the user’s plots.

R Packages: This is where the user can view a list of all the installed packages

R Help: This is where you can browse the built-in Help system of R

6. R Scripting

Let us start scripting in R.

Let’s create a script to print “Hello world!” in R. To create scripts in R, you need to perform the following steps:

Here in R, you will have to enclose some commands in print() to get the same output as on the command line. So you need to type below command: This takes “Hello World” as input in R.

> print (“Hello world!”)

We get the output as:

[1] “Hello world!”

7. Doing Simple Math in R

R can be used like a calculator as one of its principal uses is to undertake complex mathematical and statistical calculations. R can perform simple calculations as well as complex ones, but generally these are made up of smaller elements.

Let’s create a script that performs mathematical operation in R. To create scripts in R, you need to perform the following steps:

> 3 + 9 + 12 - 7

Above is given as input to R and we get the output as below:

[1] 17

This means R works like a calculator where you need to type an expression to get the answer.

R uses standard rules and use the standard principle of BODMAS according to which the multiplication and division operations are done first, followed by the additions and subtractions operations, respectively. If parentheses are used, a quite different result is obtained.

For example:

> (12 + 17/2 -3/4) * 2.5
[1] 49.375

8. Mathematical Operations in R

Let us see mathematical operations in R:

An operator is a symbol that when placed between 2 values make a calculation. Below are few operators in R:

The standard arithmetic operators are +, -, *, and / for add, subtract, multiply and divide, and ^ for exponentiation.

  • Pi – Value of pi is approximately 3.142
  • Sqrt(X) – Square Root of x
  • cos(x) sin(x) tan(x) acos(x) asin(x) atan(x) – Trigonometric functions for cosine, sine, tangent, arccosine, arcsine, and arctangent, respectively in radians
  • log(x, base = n) – The logarithm of x using base = n (natural log if none specified)

9. R Vectors

A vector in R is the simplest type of data structure. A vector, in programming, is a one dimensional array.

The R manual defines a vector as “a single entity consisting of a collection of things;” for example, a collection of numbers is a numeric vector. The first five integer numbers form a numeric vector of length 5.

Let us learn how to use vectors in R.

The function c, which is short for concatenate can be used to create vectors from scalars or other vectors.

> c(1,2,3,4,5)

This is the command to create vector with first five integers in R. Entries inside the parenthesis are referred to as arguments.

Vectors can also be created using operators in R.

> 1:5

This will give output as below:

[1] 1 2 3 4 5

10. Storing and Calculating Values

If we use R coding for just performing arithmetic calculations then the task of noting and utilizing the intermediate results while performing a series of operations, increases complexity; therefore, R provides with a much more useful capability. You can easily store the intermediate results in R. The stored values can be used later for performing further calculations.

Vectors in R can be used for storing values like:

> x <- 1:5    //(Input the numbers in a vector in R)
> x   //(Command to display contents of vector in R)

This will show contents of vector as

[1] 1 2 3 4 5    

In R, the assignment operator is /<–/, which can be entered by using the less than symbol (<) followed by a hyphen (–). The combination of these two symbols represents the assignment operator. In addition to retrieving the value of a variable, further calculations can be performed on the values stored in a variable.

Let us see how to add variables in R:

> x <- 1:5    //(Input the numbers in a vector x)
> y <- 10    //(inputs the number in vector y)
> x + y    //(Is the command to display the contents of the vector in R)

This will show contents of vector as

[1] 11 12 13 14 15

We can also combine text values in R as below:

> hw <- c("Hello", "world!")    //(This is the command to input text values)
> hw    //(this is the command to display contents of vector)

This gives output as below:

[1] "Hello" "world!"

Let us see how to create variable and print its value in R:

> z <- x + y    //(This command inputs the variables)
> z    //(This command display the contents of the vector)

This shows the contents of the vector as

[1] 11 12 13 14 15

11. Talking Back to the User in R

R scripts can be developed to interact with users. The readline() function is used to ask questions from the user, as follows:

> h <- "Hello"    // (Inputs text value to variable)
> yourname <- readline("What is your name?") What is your name?Andrie    //(This command Inputs text value to yourname file)
> paste(h, yourname)    //(This command shows the implementation of paste() function)

We get the output of above function as below:

[1] "Hello Andrie"

In the preceding code, a value is read from the keyboard and then assigned to the yourname variable. It would be much better to send these three lines of code simultaneously to R and get them evaluated in one go.

12. Sourcing a Script in R

R provides the feature to develop scripts in external editors and then import in R for execution. This is known as sourcing a script. Individual line of code or a block or entire script can be sourced in R in RGUI or RStudio as below:

Multiple lines of code can be entered in the source editor without having each line evaluated by R. Once the scripting is completed, the entire script can be sent to R. In other words, you can source the script

Script can be sourced in either Rgui or Rstudio in the following ways:

To send an individual line of code from the editor to the console:

  • In RGUI, Click the line of code and then press Ctrl+R to execute the instruction.
  • In RStudio, press Ctrl+Enter or click the Run button to execute the instruction.

To send a block of highlighted code to the console:

  • Select the block that needs to be executed and then press Ctrl+R in RGui or Ctrl+Enter in RStudio.

To send the entire script to the console:

  • In RGui, click anywhere in the script window, and then choose EditðRun all.
  • In RStudio, click anywhere in the source editor and press Ctrl+Shift+Enter or click the Source

These keyboard shortcuts are defined only in RStudio. In different source editor, these options may be different.

Now the entire script can be sent to the R console. To do this, click the Source button at the top right corner of the editor window or choose edit→Source. The script starts, reaches the point where it asks for input, and then waits for the user to enter the name in the console window.

13. Navigating the R Workspace

Let us first learn workspace:

Workspace refers to all the variables and functions that are created during any active R session as well as any packages that are loaded.

To see the list of the variables created in the workspace, ls() function is used as follows:

> ls()

This is used to display the list of the variables created in the workspace.

RStudio lets the user examine the contents of the workspace at any time without typing any R commands. In the RStudio, by default, the top right window has two tabs: Workspaceand History. Click the Workspacetab to see the variables in the active workspace.

The content of the workspace can be manipulated using the rm() and ls() functions. The rm() function can be used as follows:

> rm()

This is used to remove the specified variables from the workspace.

This is how workspace navigation can be done.

14. Saving Your Work in R

R provides the following options for saving work:

  • To save individual variables, the save() function is used.
  • To save the entire workspace, save.image() function is used.
  • The R script file can be saved using the appropriate save menu command in the code editor.

The saved content can be loaded in the R workspace using the load() function, as follows:

  • > load(“file_name.rdata”)

This is used to load the specified file from memory to current workspace.

Reference:

https://en.wikipedia.org/wiki/R_(programming_language)


Leave a comment

Your email address will not be published. Required fields are marked *

2 thoughts on “R Programming – A Quick Introduction