R Lecture 4 Naomi Altman Department of Statistics Department of Statistics (Based on notes by J....

25
R Lecture 4 R Lecture 4 Naomi Altman Naomi Altman Department of Department of Statistics Statistics (Based on notes by J. Lee) (Based on notes by J. Lee)

Transcript of R Lecture 4 Naomi Altman Department of Statistics Department of Statistics (Based on notes by J....

R Lecture 4R Lecture 4

Naomi AltmanNaomi Altman Department of StatisticsDepartment of Statistics

(Based on notes by J. Lee)(Based on notes by J. Lee)

Matrix ComputationsMatrix Computationsmatrix creates matricesmatrix creates matrices

array creates higher dimensional array creates higher dimensional

arraysarrays

binary operations such as +, -, * , /binary operations such as +, -, * , /

>,<>,<

are done element-wise, and create a new are done element-wise, and create a new matrix or array the same size as the matrix or array the same size as the larger arraylarger array

More Matrix OperationsMore Matrix Operationsmore matrix operationsmore matrix operations

%*% matrix multiplication%*% matrix multiplication

t transposet transpose

Also: various matrix decompositionsAlso: various matrix decompositions

matrix types (e.g. diag)matrix types (e.g. diag)

matrix functions such as determinant, matrix functions such as determinant,

eigenvalueseigenvalues

inverse via the "solve" functioninverse via the "solve" function

Session: Arrays + MatricesSession: Arrays + Matrices

z <- 1:150z <- 1:150 a <- array(z,dim=c(3,5,10))a <- array(z,dim=c(3,5,10)) dim(z) <- c(3,5,10)dim(z) <- c(3,5,10)aazzmatrix(1:6,nrow=2,ncol=3)matrix(1:6,nrow=2,ncol=3)matrix(1:6,nrow=2, ncol=3, byrow=T)matrix(1:6,nrow=2, ncol=3, byrow=T)

x <- matrix(0,nc=5,nr=5); x <- matrix(0,nc=5,nr=5);

i <- matrix(1:4,5,2); i <- matrix(1:4,5,2);

x[i] =1x[i] =1

matrix(1:6, 3, 2)*matrix(1:6*2, 3, 2)matrix(1:6, 3, 2)*matrix(1:6*2, 3, 2)

X = matrix(1:6,3,2)X = matrix(1:6,3,2)

y = 1:3y = 1:3

t(X) %*% yt(X) %*% y

A <- matrix(c(1,1,2,3),2,2)A <- matrix(c(1,1,2,3),2,2)

b <- c(2,5)b <- c(2,5)

solve(A,b)solve(A,b)

diag(rep(1,2))diag(rep(1,2))

solve(A,diag(rep(1,2)))solve(A,diag(rep(1,2)))

Control StructuresControl Structures

for (x in set){operations}for (x in set){operations}

while (x in condition){operations}while (x in condition){operations}

repeat {operations, test, break}repeat {operations, test, break}

if (condition) {operations}if (condition) {operations}

else {more operations}else {more operations}

switch(flag,dolist)switch(flag,dolist)

Control Structures: Session 1Control Structures: Session 1x <- 1:9x <- 1:9if (length(x) <= 10) {if (length(x) <= 10) { x <- c(x,10:20);print(x) }x <- c(x,10:20);print(x) }if (length(x) < 5) print(x) if (length(x) < 5) print(x) else print(x[5:20])else print(x[5:20])for (i in x) ifor (i in x) ifor(i in x) {print(i)}for(i in x) {print(i)}y=c("a","b","hi there")y=c("a","b","hi there")for (i in y) ifor (i in y) ifor (i in y) print(i)for (i in y) print(i)

j <- 1j <- 1

while( j < 10) {while( j < 10) {

print(j)print(j)

j <- j + 2 }j <- j + 2 }

j < -1j < -1

repeat {repeat {

print(j)print(j)

j <- j + j/3j <- j + j/3

if (j > 30) breakif (j > 30) break

}}

citizen="uk"citizen="uk"

switch(citizen,au="Aussie",uk="Brit",us="Yswitch(citizen,au="Aussie",uk="Brit",us="Yankee",ca="Canuck")ankee",ca="Canuck")

FunctionsFunctionsFunctions are stored like data.Functions are stored like data.

my.function=function(arguments){operations}my.function=function(arguments){operations}

I write functions for just about anything I need to I write functions for just about anything I need to do more than once - I run through the do more than once - I run through the commands once interactively, and then use the commands once interactively, and then use the history() feature and an editor to create the history() feature and an editor to create the function.function.

It is wise to include a comment at the start of each It is wise to include a comment at the start of each function to say what it does and to document function to say what it does and to document functions of more than a few lines.functions of more than a few lines.

e.g. makeList=function(mat,i=2){e.g. makeList=function(mat,i=2){#change a matrix into a list of rows or columns#change a matrix into a list of rows or columns mylist=list()mylist=list() m=switch(i,t(mat),mat)m=switch(i,t(mat),mat) for (i in 1:ncol(m)){for (i in 1:ncol(m)){ mylist[[i]]=m[,i] mylist[[i]]=m[,i] }} mylistmylist }}

Calling Conventions for FunctionsCalling Conventions for Functions

Arguments may be specified in the same Arguments may be specified in the same order in which they occur in function order in which they occur in function definition, in which case the values are definition, in which case the values are supplied in order.supplied in order.

Arguments may be specified as Arguments may be specified as name=value, when the order in which the name=value, when the order in which the arguments appear is irrelevant. arguments appear is irrelevant.

Above two rules can be mixed.Above two rules can be mixed. t.test(x1, y1, var.equal=F, conf.level=.99)t.test(x1, y1, var.equal=F, conf.level=.99) t.test(var.equal=F, conf.level=.99, x1, y1)t.test(var.equal=F, conf.level=.99, x1, y1)

Default valuesDefault valuesWhen creating a function, the programmer When creating a function, the programmer

can supply default values.can supply default values.

makeList=function(mat,i=2){}makeList=function(mat,i=2){}

means that by default, i=2. The user can means that by default, i=2. The user can change the value when calling the change the value when calling the functionfunction

myRowList=makeList(mymat,1)myRowList=makeList(mymat,1)

Missing ArgumentsMissing Arguments

R functions can handle missing R functions can handle missing arguments two ways either by arguments two ways either by providing a default expression in the providing a default expression in the argument list of definition, or by argument list of definition, or by testing explicitly for missing testing explicitly for missing arguments. arguments.

Session: Missing ArgumentsSession: Missing Arguments

add <- function(x,y=0){#adds 2 numbersadd <- function(x,y=0){#adds 2 numbers

x + y}x + y}

add(4)add(4)

add <- function(x,y){#adds 2 numbers add <- function(x,y){#adds 2 numbers if(missing(y)) xif(missing(y)) x

else x+yelse x+y

}}

add(4)add(4)

Variable Number of ArgumentsVariable Number of Arguments

The special argument name “…” in The special argument name “…” in the function definition will match any the function definition will match any number of arguments in the call.number of arguments in the call.

nargs() returns the number of nargs() returns the number of arguments in the current call. arguments in the current call.

Variable Number of ArgumentsVariable Number of Arguments

mean.of.all <- function(…) mean(c(…))mean.of.all <- function(…) mean(c(…))

mean.of.all(1:10,20:100,12:14)mean.of.all(1:10,20:100,12:14)

mean.of.means <- function(…){mean.of.means <- function(…){

means <- numeric()means <- numeric()

for(x in list(…)) means <- for(x in list(…)) means <- c(means,mean(x))c(means,mean(x))

mean(means)mean(means)

}}

Session 2: Variable Number of ArgumentsSession 2: Variable Number of Arguments

mean.of.means <- function(…){mean.of.means <- function(…){

#computes the mean of the means of the#computes the mean of the means of the

# arguments# arguments

n <- nargs()n <- nargs()

means <- numeric(n)means <- numeric(n)

all.x <- list(…)all.x <- list(…)

for(j in 1:n) means[j] <- mean(all.x[[j]])for(j in 1:n) means[j] <- mean(all.x[[j]])

mean(means)mean(means)

}}

mean.of.means(1:10,10:100)mean.of.means(1:10,10:100)

Variables are localVariables are local

Note that Note that any ordinary assignments done any ordinary assignments done within the function are local and within the function are local and temporary and lost after exit from the temporary and lost after exit from the functionfunction. .

fun1 <- function(){fun1 <- function(){ a <- 1:10a <- 1:10 rnorm(10)rnorm(10)}}aa

Output from a functionOutput from a functionThe last line of a function should be the output.The last line of a function should be the output.

myfun=function(x){myfun=function(x){

y=3*xy=3*x

y}y}

myfun=function(x){myfun=function(x){

y=3*xy=3*x

list(x=x,y=y)list(x=x,y=y)

}}

EditEditfunname=edit(myfun)funname=edit(myfun)

brings up an edit window.brings up an edit window.

If funname is the same as myfun, you will save the edited If funname is the same as myfun, you will save the edited function, overwriting myfun.function, overwriting myfun.

If you make a syntax error, when editing, R will send you an If you make a syntax error, when editing, R will send you an error message upon closing the edit window and will not error message upon closing the edit window and will not save the changes.save the changes.

funname=edit()funname=edit()

will bring up the most recent edit windowwill bring up the most recent edit window

Session 3: Editing a functionSession 3: Editing a function

?append?append

appendappend

x=(1:10)*4x=(1:10)*4

append(x,3,after=4)append(x,3,after=4)

myappend=edit(append)myappend=edit(append)

myappend(x,3,after=4)myappend(x,3,after=4)

Functions calling FunctionsFunctions calling FunctionsWhen a function calls another function, you When a function calls another function, you

need to be careful to understand which need to be careful to understand which variables are local to which functions. variables are local to which functions.

This is called "scope" and is discussed in the This is called "scope" and is discussed in the tutorial. (10.7)tutorial. (10.7)

One of the few differences between Splus One of the few differences between Splus and R pertain to "scope" and so it is and R pertain to "scope" and so it is important to understand this if you are important to understand this if you are trying to port functions between them.trying to port functions between them.

Documenting your FunctionsDocumenting your FunctionsYou will quickly lose track of all your You will quickly lose track of all your

functions unless you document them.functions unless you document them.

Comments should be added to all Comments should be added to all functions. If you plan to share the functions. If you plan to share the functions, the comments should at least functions, the comments should at least include a list of the function arguments include a list of the function arguments and outputs.and outputs.

You can also create help documents that You can also create help documents that will respond to ?will respond to ?

Creating a Help FileCreating a Help File

R has a mark-up language for creating R has a mark-up language for creating help files for your functions and other help files for your functions and other objects.objects.

We will look at this for a homework.We will look at this for a homework.