Microsoft Excel which is a part of Microsoft Office is the most widely used spreadsheet program it stores data in the .xls or .xlsx format.
R can read these files but it needs to install specific packages to do this.
XLConnect, xlsx, gdata etc. are few of the packages that can be installed to read excel files.
In this demonstration we will be using xlsx package also R can write into excel file using this package.
To create and run our R program in Visual Studio we must first install some tools.
Now open Visual Studio on your pc and then click on Get Tools and features… inside Tools>
Now in the feature installation window check and install the following features
For Visual Studio 2017
Contains Tools for Data Science
After this please install R tools from the following link if the above package is not installed properly from the following link
But it is not necessary
You can also install R programming tool go to the following link for better support and download the software and install it.
For Windows Users:
Type the following command in Visual Studio or R Interactive:
For Linux Users:
If you are on Linux platform then you can use this fast and easy command used in Linux which can be used to install R. The yum command is used for installing like this:
$ yum install R
For Ubuntu Linux or other Debian-related OSs, a more direct method is:
$ apt-get install r-base
Now let us start creating our R application in visual studio
Go to Files ->Project and add a new R project
This is our project structure:
Now on the top left side is a new R file (script.R) where we can edit source code with all of Visual Studio Ide editing features.
Also on the bottom left of Visual Studio is where you can find an R Interactive window in which you can interactively develop and test code.
We can directly use R Interactive without the need of opening any new project.
Getting and Setting the Working Directory
We can check which directory the R tool in visual studio is pointing to using the
You can also set a new working directory using
# Get and display default working directory.
# Set current working directory to user Defined.
# Get and display altered working directory.
Now to verify and load ‘’xlsx” package
# Verify the package is installed.
# Load the library into R workspace.
After running the script is run we get the following output:
To supply data to our dataframe we will use a pre-existing source which is present in R it consists of details of different cars produced in 1973-74.
# Calling the xlsx library
#Inserting data into dataframe and printing it
a <- mtcars
#Getting the default directory
#Writing excel files in the directory which was specified in the document above
write.xlsx(mtcars, file=”1.xlsx”, sheetName=”cars” , row.names = FALSE)
#Reading the Excel files
res <- read.xlsx(file="1.xlsx", 1)