R: Loading Data into R


There are a few different ways to load data into R. Below are the most useful (to me) with examples:

CSV file

If you use the table function, you must specify the seperator.

# Read in csv files
df <- read.table("  ", header = FALSE, sep = ",")

If you specify the csv function, it will use a comma-delimited separator.

df <- read.csv("https://s3.amazonaws.com/assets.datacamp.com/blog_assets/test.csv", header = FALSE)

If you specify csv2 method, it will use a semicolon (;) separator.

df <- read.csv2("https://s3.amazonaws.com/assets.datacamp.com/blog_assets/test.csv", header= FALSE)

You can also use the readr library if you prefer.

# Import your library
# Import the csv file

Txt file

Tab delineated text file.

df <- read.table("<FileName>.txt", sep="\t", header = TRUE)

Carriage return delineated text file.

df <- read.table("<FileName>.txt", sep="\r", header = TRUE)

If your file uses something other an ,, ;, \t, such as a |, then the delim method is very handy.

# Read a delimited file
df <- read.delim("https://s3.amazonaws.com/assets.datacamp.com/blog_assets/test_delim.txt", sep="$") 

Excel file

We use XLConnect package to import Excel files.


Read an Excel worksheet from the file.

df <- readWorksheetFromFile("<file name and extension>", 
                            startRow = 4,
                            endCol = 2)

JSON file

Import an external JSON file.
We use rjson library to work with JSON files.


# Import data from json file
JsonData <- fromJSON(file= "<URL to your JSON file>" )

XML file

Import an external XML file.


xmlfile <- xmlTreeParse("<Your URL to the XML data>")

Dynamically Loading from a Web Server


web <- "https://raw.githubusercontent.com/alstat/Analysis-with-Programming/master/2013/R/How%20to%20Enter%20Your%20Data/Data.dat"

x <- getURL(web)

y <- read.table(text = x, header = TRUE)


XLConnect + rJava on macOS

Read my article on how to troubleshoot installing XLConnect and rJava on macOS.


Check if a library is already installed

If you want to see if ggplot2 or shiny packages are installed, here's how.

any(grep("<name of package>", installed.packages()))