Reading files in R

Clear your workspace at the start of every sesion with the following command

rm(list=ls()) 

You can set your work directory with setwd()

Navigate to your Rainfall folder

setwd('/Users/mpetric/Desktop/Datasets/Met_data/Rainfall')

However this is the syntax for MAC, for WINDOWS you will set your work directory as >

setwd(C:\\...\\my documents\\Rainfall)

Check the contents of your folder by typing

dir()

you should see the ‘IE_RR_8110_V1.txt’ and ‘Readme.txt’ files

Since it’s writen in the coma separated format use

read.csv()  

to read the rainfall data and store it in a variable called prec

prec<-read.csv('IE_RR_8110_V1.txt',header=TRUE)

With View() you can preview your file, type

View(prec) 

in the R console and see what hapens.

Reading excel files + installing R packages (the most important thing in R)

A lot of R functions are stored in “packages” which you have to install and unpack to be able to use them in your code. It’s really neat. There’s a package for dealing with excel files, for looking at raster data, for probabilistic calculations and so forth.

To install a package, type

install.packages('xlsx')

and to unpack and load the libraries from that package type

library(xlsx)

Now you have access to a buch of functions that let you view and manipulate excel files:) Yay

To read an xlsx file use the following

x<-read.xlsx2("example.xlsx",sheetIndex = 1,header=TRUE)

The header arguments let’s you specify if your data has column names in it so that R starts reading records from the second row onward.

(You can create aa excell file and try it out if you want)

Remember that the file you want to open has to be in the directory matching your current work directory.

You can check your work directory by typing

getwd()
## [1] "/Users/mpetric/Desktop/Datasets/Met_data/Rainfall"

and you change it with

setwd('C:\\..\\')

as we did above.

Let me know if you have any questions, Mina