R Data Import

Working Directory

To get our project's working directory, run the following code:

getwd()

To set our working directory:

setwd("FOO/BAR/PATH")

Importing From Various File Extensions

Excel

Using gdata package:

library(gdata)		# loads gdata package
mydata = read.xls("mydata.xls")	# read first sheet

Using XLConnect package:

library(XLConnect)
wk = loadWorkbook("mydata.xls")
df = readWorksheet(wk, sheet="Sheet1") # loads Sheet1 of mydata.xls

Minitab

Using foreign package:

library(foreign)
mydata = read.mtp("mydata.mtp")

SPSS

Using foreign package:

library(foreign)
mydata = read.spss("myfile", to.data.frame=TRUE)

Table

A dataset can be written in a plain text file, but every cell must be separated by blank spaces.

Example dataset mydata.txt:

123 asd dsa
321 sda sad
432 rtr oko
952 msk tiw
492 nas oaq

Loading the file:

mydata = read.table("mydata.txt")
mydata # prints the content

CSV (Comma Separated Values)

Normally, a csv file contains columns that is separated by commas. A row is separated by a new line.

mydata = read.csv("mydata.csv")
mydata								# prints the content

Creating Basic Data

Creating our own basic dataset to experiment with, we're going to use c() function:

col1 = c(2, 3, 4)
col2 = c("hello", "world", "hi")
col3 = c(TRUE, FALSE, FALSE)
df = data.frame(col1, col2, col3)

Source

Show Comments

Get the latest posts delivered right to your inbox.