How to import an Excel file in R

In order to import an excel file directly into R, without the need to convert it into a CSV file, and create a data frame (i.e. a dataset), we could use the XLConnect library. We will install the library, and call it right away to work, by typing this:

 

install.packages("XLConnect")                                                       #install package
library("XLConnect")                                                                      #calling library

Lets say we have a file called 'file.xlsx' store in D:/data/, from which we want to read the sheet 'info'. To read this file directly, we use the following code:

info <- readWorksheetFromFile("d:/data/file.xlsx", sheet = "Info")   #opening file / directly

This code will create an object call info, which contains in a data frame, the contents of our excel file. Sometimes, excel files may have different characters, in which teh viewer in R (with R Studio, or Rcmdr) may not able to handle. Characters such as ñ,á,é,í,ó or maybe others. To check if the data was read properly we could export it to text, to see how it looks. 

write.table(info, "d:/data/info.txt", sep="\t")                       #export data to see how it looks

We could also export the data, into an excel file again, to see how it looks.

require(XLConnect)                                                                     #it specifies that for the following command, an specific library needs to be used
writeWorksheetToFile("info.xlsx", data = info, sheet = "info")       #export data to see how it looks in excel
 

 

This is a fairly good start to do things in R.

[need to fix the blog, to store code properly, like here]

0 comments:

Post a Comment