R Studio makes it easy to import local Excel files through its "Files" panel. However, R can be used in an entirely text-based environment as well -- where one isn't afforded the luxury of R Studio's graphical user interface (GUI). However, one can easily import local Excel files into R as data frames without any of that GUI stuff, by using the readxl
package.
To use the package, you must first install it with
install.packages("readxl")
Then you need to load the library within the package just installed. You only have to execute this once in a given R session, and can do it very simply with:
> library("readxl")
Now, you might find it helpful to save the excel workbook you wish to import into R's current working directory.
To find out what the current working directory is, simply type getwd()
as shown below:
> getwd() [1] "/Users/oser"
In the example above -- which was run on a mac -- the current directory is the folder named "oser" inside the folder named "Users" at the root level. If you run this on a windows machine, your path may look different (e.g. "C:\Users\oser"
).
If you wish to change your working directory in R, you can use the setwd()
, as shown in the two examples below:
> setwd("/Users/oser/Desktop/") # <-- mac example
> setwd("C:\Users\oser\Desktop\") # <-- windows example
Note, nothing is returned as a result of executing this function -- that is normal.
Once your Excel file is in R's working directory, you are ready to import the data into R. Suppose we wish to import the data from the Excel file samples.xlsx
shown below and this file is in the working directory.
We simply type something similar to :
> excelData = read_excel("samples.xlsx")
Now we can access the individual columns of data in the normal data-frame-based way:
> excelData$sample1 [1] 1 3 4 7 8 13 > excelData$sample2 [1] 2 2 3 5 8 10