Saturday, October 4, 2008

Importing data into R

We'll cover two scenarios: 1) you have your data in a .csv (comma delimited) file, 2) you have your data in a .xls (Excel) file.

In either case, your data should be formated to have the first row as the variable name and the next rows as the data:

age weight other
12 25 63
13 67 67
... ... ...

-.csv files-

For .csv files, R has a built-in function that you can use to sort of "upload" you data:
read.csv(file.choose())

This will open a little window where you can browse and select your .csv file.
Or, if you know the exact location of your file, you can use (I made a folder on my desktop and a file named data1.csv):

read.csv("C:\\Users\\Andrew\\Desktop\\Desktop Folder\\data1.csv")
(For some reason you have to use double back-slashes. I don't know why.)

-Excel files-

The package 'xlsReadWrite' has a function read.xls to read .xls files.
Funny thing is, this package doesn't come installed in R. No worries. Use the code:
install.packages('xlsReadWrite')
and follow the onscreen instructions.

Then, "load" this package with:
library(xlsReadWrite)
And you're ready to go.

The logic is the same as with the 'read.csv' command- just replace all '.csv' to '.xls':
read.xls(file.choose())
read.xls("C:\\Users\\Andrew\\Desktop\\Desktop Folder\\data1.xls")


-All codes used-

read.csv(file.choose())
read.csv("C:\\Users\\Andrew\\Desktop\\Desktop Folder\\data1.csv")


install.packages('xlsReadWrite')
library(xlsReadWrite)


read.xls(file.choose())
read.xls("C:\\Users\\Andrew\\Desktop\\Desktop Folder\\data1.xls")

No comments: