Import data from excel into к

Looking to import an Excel file into R?

If so, you’ll see the full steps to import your file using the readxl package.

To start, here is a template that you can use to import an Excel file into R:

library("readxl")
read_excel("Path where your Excel file is stored\File Name.xlsx")

And if you want to import a specific sheet within the Excel file, then you may use this template:

library("readxl")
read_excel("Path where your Excel file is stored\File Name.xlsx",sheet = "Your sheet name") 

Note: For previous versions of Excel, use the file extension of .xls

Step 1: Install the readxl package

In the R Console, type the following command to install the readxl package:

install.packages("readxl")

Follow the instructions to complete the installation. You may want to check the following guide that explains how to install a package in R.

Step 2: Prepare your Excel File

Let’s suppose that you have an Excel file with some data about products:

Product Price
Refrigerator 1200
Oven 750
Dishwasher 900
Coffee Maker 300

And let’s say that the Excel file name is product_list, and your goal is to import that file into R.

Step 3: Import the Excel file into R

In order to import your file, you’ll need to apply the following template in the R Editor:

library("readxl")
read_excel("Path where your Excel file is stored\File Name.xlsx")

For demonstration purposes, let’s assume that an Excel file is stored under the following path:

C:\Users\Ron\Desktop\Test\product_list.xlsx

Where:

  • product_list is the actual file name; and
  • .xlsx is the Excel file extension. For previous versions of Excel, use the file extension of .xls

Note that a double backslash (‘\’) was used within the path name. By adding a double backslash, you’ll avoid the following error in R:

Error: ‘U’ used without hex digits in character string starting “”C:U”

Here is the complete code to import the Excel file for our example:

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

You’ll need to adjust the path to reflect the location where the Excel file is stored on your computer. Once you run the code in R, you’ll get the same values as in the Excel file:

  Product       Price
1 Refrigerator   1200
2 Oven            750
3 Dishwasher      900
4 Coffee Maker    300

Alternatively, you may also want to check the following guide that explains how to export your data to an Excel file.

In this article, we will discuss how to import an excel file in the R Programming Language. There two different types of approaches to import the excel file into the R programming language and those are discussed properly below.

File in use:

Method 1: Using read_excel()

In this approach to import the Excel file in the R, the user needs to call the read_excel() function from readxl library of the R language with the name of the file as the parameter. readxl() package can import both .xlsx and .xls files. This package is pre-installed in R-Studio. With the use of this function, the user will be able to import the Excel file in R.

Syntax: read_excel(filename, sheet, dtype = “float32”)

Parameters:

  • filename:-File name to read from.
  • sheet:-Name of the sheet in Excel file.
  • dtype:-Numpy data type.

Returns:

The variable is treated to be a data frame.

Example:

R

library(readxl)

gfg_data=read_excel('Data_gfg.xlsx')

gfg_data

Output:

Method 2: Using inbuilt menu Options of Rstudio

This approach is the easy approach to import the excel file in R compared with the previous one as this is the only approach to import an excel file in R where the user need not type any code in the console to import the excel file. Further, here user just needs to work on the environment window of the studio.

Environment window of the Rstudio:

Steps to import excel file using Dataset option from the environment window of Rstudio:

Step 1: Select the Import Dataset option in the environment window. Here the user needs to select the option to import the dataset from the environment window in Rstudio.

Step 2: Select the option of “From excel” under the import Dataset option. In this step, the user needs to select the option to “from excel” as the file is in the form of excel under the import dataset option to import the excel file.

Step 3: Select the browse option and select the excel file to be imported. Now, under this with the click to the browse option user will be given the choice to select the needed excel file to be imported in R.And then the user need to select the needed excel file to be imported in R.

Step 4: Select the import option and the excel file is successfully imported. Now, in this final step user need to select the import button and this will lead to successful importation of the selected excel file by the user in R.

The user chose the dataset according to their choice means that changing the name of the file and type of sheet. May be there are 2 sheets , he choose 2nd one then he choose the 2nd list with the help of sheet option and in max rows how much rows he wants from the data he put into it. And in  skip box , he skips the rows how much he want. In NA box, he write some value in it , if this value is in the data then it makes as NA.

There is also another method for to import the excel files into R-Studio.
Step 1: Click on file
Step 2: In file, click import dataset then choose from excel.


The easiest way to import an Excel file into R is by using the read_excel() function from the readxl package.

This function uses the following syntax:

read_excel(path, sheet = NULL)

where:

  • path: Path to the xls/xlsx file
  • sheet: The sheet to read. This can be the name of the sheet or the position of the sheet. If this is not specified, the first sheet is read.

This tutorial provides an example of how to use this function to import an Excel file into R.

Example: Import an Excel File into R

Suppose I have an Excel file saved in the following location:

C:UsersBobDesktopdata.xlsx

The file contains the following data:

Import Excel into R

The following code shows how to import this Excel file into R:

#install and load readxl package
install.packages('readxl')
library(readxl)

#import Excel file into R
data <- read_excel('C:\Users\Bob\Desktop\data.xlsx')

Note that we used double backslashes (\) in the file path to avoid the following common error:

Error: 'U' used without hex digits in character string starting ""C:U"

We can use the following code to quickly view the data:

#view entire dataset
data

#A tibble: 5 x 3
 team  points  assists
 <chr>   <dbl>   <dbl>
1 A         78      12
2 B         85      20
3 C         93      23
4 D         90       8
5 E         91      14

We can see that R imported the Excel file and automatically determined that team was a string variable while points and assists were numerical variables.

Additional Resources

The following tutorials explain how to import other file types into R:

How to Import CSV Files into R
How to Import SAS Files into R
How to Manually Enter Raw Data in R


For a solution that is free of fiddly external dependencies*, there is now readxl:

The readxl package makes it easy to get data out of Excel and into R.
Compared to many of the existing packages (e.g. gdata, xlsx,
xlsReadWrite) readxl has no external dependencies so it’s easy to
install and use on all operating systems. It is designed to work with
tabular data stored in a single sheet.

Readxl supports both the legacy .xls format and the modern xml-based
.xlsx format. .xls support is made possible the with libxls C library,
which abstracts away many of the complexities of the underlying binary
format. To parse .xlsx, we use the RapidXML C++ library.

It can be installed like so:

install.packages("readxl") # CRAN version

or

devtools::install_github("hadley/readxl") # development version

Usage

library(readxl)

# read_excel reads both xls and xlsx files
read_excel("my-old-spreadsheet.xls")
read_excel("my-new-spreadsheet.xlsx")

# Specify sheet with a number or name
read_excel("my-spreadsheet.xls", sheet = "data")
read_excel("my-spreadsheet.xls", sheet = 2)

# If NAs are represented by something other than blank cells,
# set the na argument
read_excel("my-spreadsheet.xls", na = "NA")

* not strictly true, it requires the Rcpp package, which in turn requires Rtools (for Windows) or Xcode (for OSX), which are dependencies external to R. But they don’t require any fiddling with paths, etc., so that’s an advantage over Java and Perl dependencies.

Update There is now the rexcel package. This promises to get Excel formatting, functions and many other kinds of information from the Excel file and into R.

  • Preleminary tasks
  • Copying data from Excel and import into R
    • On Windows system
    • On Mac OSX system
  • Importing Excel files into R using readxl package
    • Installing and loading readxl package
    • Using readxl package
  • Importing Excel files using xlsx package
    • Installing and loading xlsx package
    • Using xlsx package
    • Read more
  • Summary
  • Related articles
  • Infos

Previously, we described the essentials of R programming and some best practices for preparing your data. We also provided quick start guides for reading and writing txt and csv files using R base functions as well as using a most modern R package named readr, which is faster (X10) than R base functions.

In this article, you’ll learn how to read data from Excel xls or xlsx file formats into R. This can be done either by:

  • copying data from Excel
  • using readxl package
  • or using xlsx package

Reading Data From Excel Files (xls|xlsx) into R

Preleminary tasks

  1. Launch RStudio as described here: Running RStudio and setting up your working directory

  2. Prepare your data as described here: Best practices for preparing your data

Copying data from Excel and import into R

On Windows system

  1. Open the Excel file containing your data: select and copy the data (ctrl + c)

  2. Type the R code below to import the copied data from the clipboard into R and store the data in a data frame (my_data):

my_data <- read.table(file = "clipboard", 
                      sep = "t", header=TRUE)

On Mac OSX system

  1. Select and copy the data (Cmd + c)

  2. Use the function pipe(pbpaste) to import the data you’ve copied (with Cmd + c):

my_data <- read.table(pipe("pbpaste"), sep="t", header = TRUE)

Importing Excel files into R using readxl package

The readxl package, developed by Hadley Wickham, can be used to easily import Excel files (xls|xlsx) into R without any external dependencies.

Installing and loading readxl package

  • Install
install.packages("readxl")
  • Load
library("readxl")

Using readxl package

The readxl package comes with the function read_excel() to read xls and xlsx files

  1. Read both xls and xlsx files
# Loading
library("readxl")
# xls files
my_data <- read_excel("my_file.xls")
# xlsx files
my_data <- read_excel("my_file.xlsx")

The above R code, assumes that the file “my_file.xls” and “my_file.xlsx” is in your current working directory. To know your current working directory, type the function getwd() in R console.

  • It’s also possible to choose a file interactively using the function file.choose(), which I recommend if you’re a beginner in R programming:
my_data <- read_excel(file.choose())

If you use the R code above in RStudio, you will be asked to choose a file.

  1. Specify sheet with a number or name
# Specify sheet by its name
my_data <- read_excel("my_file.xlsx", sheet = "data")
  
# Specify sheet by its index
my_data <- read_excel("my_file.xlsx", sheet = 2)
  1. Case of missing values: NA (not available). If NAs are represented by something (example: “—”) other than blank cells, set the na argument:
my_data <- read_excel("my_file.xlsx", na = "---")

Importing Excel files using xlsx package

The xlsx package, a java-based solution, is one of the powerful R packages to read, write and format Excel files.

Installing and loading xlsx package

  • Install
install.packages("xlsx")
  • Load
library("xlsx")

Using xlsx package

There are two main functions in xlsx package for reading both xls and xlsx Excel files: read.xlsx() and read.xlsx2() [faster on big files compared to read.xlsx function].

The simplified formats are:

read.xlsx(file, sheetIndex, header=TRUE)
read.xlsx2(file, sheetIndex, header=TRUE)

  • file: file path
  • sheetIndex: the index of the sheet to be read
  • header: a logical value. If TRUE, the first row is used as column names.

Example of usage:

library("xlsx")
my_data <- read.xlsx(file.choose(), 1)  # read first sheet

Summary

  • Read Excel files using readxl package: read_excel(file.choose(), sheet = 1)

  • Read Excel files using xlsx package: read.xlsx(file.choose(), sheetIndex = 1)

Related articles

  • Previous chapters
    • R programming basics
    • Best practices in preparing data files for importing into R
    • Reading data from txt|csv files: R base functions
    • Fast Reading of Data From txt|csv Files into R: readr package
  • Next chapters
    • Exporting data from R

Infos

This analysis has been performed using R (ver. 3.2.3).

Enjoyed this article? I’d be very grateful if you’d help it spread by emailing it to a friend, or sharing it on Twitter, Facebook or Linked In.

Show me some love with the like buttons below… Thank you and please don’t forget to share and comment below!!

Avez vous aimé cet article? Je vous serais très reconnaissant si vous aidiez à sa diffusion en l’envoyant par courriel à un ami ou en le partageant sur Twitter, Facebook ou Linked In.

Montrez-moi un peu d’amour avec les like ci-dessous … Merci et n’oubliez pas, s’il vous plaît, de partager et de commenter ci-dessous!

Понравилась статья? Поделить с друзьями:
  • Import data from excel file to excel file
  • Import csv to word
  • Image will not print in word
  • Import csv from excel to mysql
  • Import csv for excel