Reading files in R programming is straightforward. This post demonstrates how to read CSV files using R’s native read_csv
function. Also, I’ll demonstrate how to read Microsoft Excel “.xlsx” files using the readxl
package.
Reading CSV Files in R Programming
Honestly, this could not be much easier. To read a CSV file in R just use the read.csv
function. You can point to the file in at least two ways:
- Set the current working directory and then specify the file name
- Use a file picker
To set the current working directory, use the setwd
function. For Windows operating systems, use the “\\” path separator to escape back slashes as in many other programming languages. For *NIX based operating systems, use the “/” path separator. Note, for my demo, I downloaded some stock ticker CSV data from Kaggle.
The code to read the stock data by setting the current working directory and then specifying the file is:
setwd(‘c:\users\localuser\documents\urprogramming\stockdata’)
csv_data <- read.csv(‘AAPL.csv’)
csv_data
That’s all that is required, and the other option using a file picker is very similar. The only change to the code is to specify the file picker in place of the actual file name.
csv_data <- read.csv(file.choose())
That’s really all there is to it:
Read Excel Files in R Programming
You can get really advanced in how you read Excel files in R using the readxl package. The library enables you to specify ranges, worksheets, cells, etc.
To install the package from CRAN, I use the following:
for (package in c(‘readxl’)) {
if (!require(package, character.only=T, quietly=T)) {
install.packages(package,repos=”https://cran.us.r-project.org”)
library(package, character.only=T)
}
}
The above is actually stripped down. I did this as part of an R Shiny project, but didn’t include all of the packages I needed for that project in the snippet above. To read the file, use the read_excel
function instead of the read.csv
function:
datafile <- input$fileupload # this is related to my R Shiny project
finalraw <- read_excel(datafile$datapath, range=cell_cols(“A:D”))
To see a quick demo of my Shiny UI, here is one of the stock files converted to XLSX and then read in with the read_excel
function as written above:
That’s all there is to it:
- To read CSV file, use the built in
read.csv
function - To read Excel files, use the CRAN package I linked to above and follow the docs
Categories: R Programming
Leave a Reply