Microsoft Excel is the most widely used spreadsheet program to store data in .xls or .xlsx format. R language can use some excel-specific packages directly from these files. Very few such packages are XLConnect, xlsx, gdata, etc. We will use the xlsx package. R language can also use this package to write to excel files.
Install xlsx package
You can use the following command in the R console to install the "xlsx" package. It may require some additional packages to be installed. Install other packages as the same command with the required package name.
("xlsx")
Verify and load the "xlsx" package
Verify and load the "xlsx" package using the following command.
# Verify the package is installed. any(grepl("xlsx",())) # Load the library into R workspace. library("xlsx")
When the script runs, we get the following output.
[1] TRUE Loading required package: rJava Loading required package: methods Loading required package: xlsxjars
Enter as xlsx file
Open Microsoft Excel. Copy and paste the following data into a worksheet called sheet1.
id name salary start_date dept 1 Rick 623.3 1/1/2012 IT 2 Dan 515.2 9/23/2013 Operations 3 Michelle 611 11/15/2014 IT 4 Ryan 729 5/11/2014 HR 5 Gary 843.25 3/27/2015 Finance 6 Nina 578 5/21/2013 IT 7 Simon 632.8 7/30/2013 Operations 8 Guru 722.5 6/17/2014 Finance
Also copy and paste the following data to another worksheet and rename this worksheet to "city".
name city Rick Seattle Dan Tampa Michelle Chicago Ryan Seattle Gary Houston Nina Boston Simon Mumbai Guru Dallas
Save Excel file as "". It should be saved in the current working directory of the R workspace.
Read Excel file
Read by using the() function as shown below. The results are stored as data frames in the R locale environment.
# Read the first worksheet in the file . data <- ("", sheetIndex = 1) print(data)
When we execute the above code, it produces the following result
id, name, salary, start_date, dept 1 1 Rick 623.30 2012-01-01 IT 2 2 Dan 515.20 2013-09-23 Operations 3 3 Michelle 611.00 2014-11-15 IT 4 4 Ryan 729.00 2014-05-11 HR 5 NA Gary 843.25 2015-03-27 Finance 6 6 Nina 578.00 2013-05-21 IT 7 7 Simon 632.80 2013-07-30 Operations 8 8 Guru 722.50 2014-06-17 Finance
This is the article about R language operating examples for Excel file operation. For more information about R language Excel file processing methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!