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
library(readr)
# Import the csv file
read_csv("/path/to/file.csv")
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.
library(XLConnect)
Read an Excel worksheet from the file.
df <- readWorksheetFromFile("<file name and extension>",
sheet=1,
startRow = 4,
endCol = 2)
JSON
file
Import an external JSON file.
We use rjson
library to work with JSON files.
library(rjson)
# Import data from json file
JsonData <- fromJSON(file= "<URL to your JSON file>" )
XML
file
Import an external XML file.
library(XML)
xmlfile <- xmlTreeParse("<Your URL to the XML data>")
Dynamically Loading from a Web Server
library(RCurl)
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)
Troubleshooting
XLConnect + rJava on macOS
Read my article on how to troubleshoot installing XLConnect and rJava on macOS.
More
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()))