Introduction to R - Duke University



Introduction to R

Opening R – click on icon

Changing directory to a folder for the current project – File>Change Directory

getting help:

?plot find the help file for the function or keyword

help(plot) find the help file for the function or keyword

help(“plot”) find the help file for the function or keyword

help.search("plot") find all help files that use the term “plot”

Help pulldown menu: multiple help options, including pdf manual

Command console:

Use up arrow to recall past commands

Variables:

- case sensitive

- types: integer, numeric, character, etc

Assigning values to variables

= or

Displaying values of variables – type name of variable (results not automatically displayed)

Displaying sizes of variables: length(x)

Matrices and vectors

n=numeric(100) create a one-dimensional array to store 100 numbers

n=array(0,c(nrow,ncol)) fill a nrow x ncol matrix n with zeros

n=matrix(0,nrow,ncol) same as above

n=matrix(m,nrow,ncol) fill a matrix with the elements of m

n=array(0,c(nrow,1)) fill a nrow x 1 column vector n with zeros

n=array(0,c(1,ncol)) fill a 1 x ncol row vector with zeros

n=array(0,c(nrow,ncol,ndep)) fill a nrow x ncol x ndep array with zeros

Accessing elements of matrices, arrays, or data frames:

n=array(1:12,c(3,4))

n[3,2] get the item in row 3, column 2 of n

n[3,] get the 3rd row of n

n[,2] get the 2nd column of n

n[-3,] get all but the 3rd row of n

n[,-(1:2)] get all but the 1st and 2nd columns of n

n[5] get the 5th item in n

Changing the dimensions of an array:

x=runif(16) create an array of 16 0-1 uniform random numbers

dim(x)=c(4,4)

Referring to variable Year in dataframe Data:

Data$Year

Logical statements:

&, |, , =, ==

(1 For a mix of points (small circles) and (solid, thick) lines in a graph and the corresponding legend:

include

type=c("p","l","l","l"),pch=21,col=c("black","blue","green","red"),lty=1,lwd=2

in the matplot command

and

pch=c(21,-1,-1,-1),col=c("black","blue","green","red"), lty=c("blank","solid","solid","solid"),lwd=2

in the legend command

[because there are no point characters with the code -1, the command pch=c(21,-1,-1,-1) tricks the legend function into not drawing points for the last 3 entries]

Multiple graphs in 1 window:

split.screen(c(2,2))

screen(1), screen(2), etc.

Multiple graphics windows:

windows() to open a new window

dev.set(2) to return to window 2 (the first one opened)

................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download