Read and write data in R

This post shows how to import data to R from numerous resources

Text File

Read a simple text file by lines

readLines('data.txt')

Table File

Reads a file in table format and creates a data frame from it

read.table('data.txt')

CSV File

Read a csv file from local or from a server

read.csv('mydata.csv')
read.csv('http://somesite.com/mydata.csv')

Compressed File

Reading in a zip data file without unzipping it

read.csv(unz("data.zip", "data.csv"))

JSON File

Handling JSON object is currently an important task when we live in era of web service where result of an api often be wrapped in a json object.

library(jsonlite)
fromJSON('data.json')
fromJSON('http://someapi.com/data.json')

read more

Excel File

Read a Microsoft Excel file into a data frame

library(gdata) 
read.xls('data.xls')

RData

In R, you can you save() function to save object or data to file and use load() function to load saved object or data. It’s very helpful, when you can save anything: data, fitted model or even plot objects.

save(variablename, file='data.rda')
load('data.rda')

SPSS, Stata, or SAS file

Read a file stored by the SPSS, Stata or SAS save or export commands.

spssdata = read.spss('spssfile.sav')
statadata = read.dta('statafile.dta')
sasdata = read.xport('sasfile.xpt')

Database Access

Database interface and driver to PostgresSQL, MySQL, Mongo, ODBC or SQLite for R

install.packages('RPostgreSQL')
install.packages('RMySQL')
install.packages('RMongo')
install.packages('RODBC')
install.packages('RSQLite')

References

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s