How to Install a Package in R (example included)

The following template can be used to install a package in R:

install.packages("package_name")

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

The same steps reviewed here can be used to install other packages in R.

Steps to Install a Package in R

Step 1: Launch R

To start, launch R on your computer.

You’ll then see the R Console:

>

Step 2: Type the command to install the required package

Use the following template to install your package:

install.packages("package_name")

For example, you may type the following command in the R Console in order to install the readxl package:

install.packages("readxl")

Once you are done typing the command, press ENTER to proceed with the installation.

Step 3: Select a Mirror for the installation

For the final step, select a Mirror for the installation.

You may choose a mirror which is closer to your geographic location.

Step 4: Start using the package installed

In order to start using the package installed, you’ll need to load it in the R Editor by clicking on “File” and then selecting “New script“.

Type the following in order load the readxl package:

library("readxl")

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

The data in the Excel file is:

ProductPrice
Laptop1200
Tablet350
Printer150
Keyboard100

For demonstration purposes, assume that the file is stored under the following path:

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

So this is the full code to import the Excel file:

library("readxl")

df = read_excel("C:\\Users\\Ron\\Desktop\\Products.xlsx")

print(df)

You’ll need to adjust the path 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).

Run the code in R, and you’ll get this table that matches with the data stored in the Excel file:

  Product  Price
1 Laptop    1200
2 Tablet     350
3 Printer    150
4 Keyboard   100