How to Install a Package in R (example included)

Often times you may need to install a package in R. In this short guide, I’ll show you how to install a package in R using a simple example.

In general, you can use this template to install a package in R:

install.packages("name of the package")

For illustration purposes, I’ll show you how to install the readxl package. This package is used to import Excel files into R.

The same steps that will be reviewed can be used to install other packages in R as well.

Steps to Install a Package in R

Step 1: Launch R

To start, you’ll need to launch R:

Launch R

You’ll then see the R Console:

R Console

Step 2: Type the command to install the package

Now you’ll need to use the following template to install your package:

install.packages("name of the package")

Since in our case, we are interested to install the readxl package, then you’ll need to type this command in the R Console:

install.packages("readxl")

This is how the command would look like in the R Console. Once you are done typing the command, press ENTER to proceed with the installation:

How to Install a Package in R (example included)

Step 3: Select a Mirror for the installation

For the final step, select a Mirror for the installation. In my case, I chose the USA (OR)[https] mirror. But you may choose a mirror which is closer to your geographic location.

 

Select Mirror in R

Step 4: Start using the package installed

To start using the package installed, you’ll need to load it in the R Editor.

For example, to load the readxl package, you’ll have to use:

library("readxl")

Let’s say that you want to import an Excel file into R (where the Excel file name is ‘Products’). The data that is stored in the Excel file is:

ProductPrice
Desktop Computer700
Tablet250
iPhone800
Laptop1200

In my case, I stored the Excel file on my Desktop under the following path:

C:\\Users\\Ron\\Desktop\\Products.xlsx

So this is the code that I used to import the Excel:

library("readxl")
read_excel("C:\\Users\\Ron\\Desktop\\Products.xlsx")

You’ll need to adjust the path name to reflect the location where the Excel file is stored on your computer (don’t forget to use double backslash within the path name to avoid any errors).

How to Install a Package in R

Run the code in R, and you would get this table which matches with the data stored in the Excel file:

Install a Package in R (example included)

CategoriesR