Download presentation

Presentation is loading. Please wait.

Published byKaiya Machin Modified about 1 year ago

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

2
Matrix Computations matrix creates matrices array creates higher dimensional arrays arrays binary operations such as +, -, *, / >,,< are done element-wise, and create a new matrix or array the same size as the larger array are done element-wise, and create a new matrix or array the same size as the larger array

3
More Matrix Operations more matrix operations %*% matrix multiplication t transpose Also: various matrix decompositions matrix types (e.g. diag) matrix types (e.g. diag) matrix functions such as determinant, matrix functions such as determinant, eigenvalues eigenvalues inverse via the "solve" function inverse via the "solve" function

4
Session: Arrays + Matrices z <- 1:150 z <- 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)azmatrix(1:6,nrow=2,ncol=3) matrix(1:6,nrow=2, ncol=3, byrow=T)

5
x <- matrix(0,nc=5,nr=5); i <- matrix(1:4,5,2); x[i] =1 matrix(1:6, 3, 2)*matrix(1:6*2, 3, 2) X = matrix(1:6,3,2) y = 1:3 t(X) %*% y A <- matrix(c(1,1,2,3),2,2) b <- c(2,5) solve(A,b)diag(rep(1,2))solve(A,diag(rep(1,2)))

6
Control Structures for (x in set){operations} while (x in condition){operations} repeat {operations, test, break} if (condition) {operations} else {more operations} else {more operations}switch(flag,dolist)

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

8
j <- 1 while( j < 10) { print(j) print(j) j <- j + 2 } j <- j + 2 } j < -1 repeat { print(j) print(j) j <- j + j/3 j <- j + j/3 if (j > 30) break if (j > 30) break}

9
citizen="uk" switch(citizen,au="Aussie",uk="Brit",us="Y ankee",ca="Canuck")

10
Functions Functions are stored like data. my.function=function(arguments){operations} I write functions for just about anything I need to do more than once - I run through the commands once interactively, and then use the history() feature and an editor to create the function. It is wise to include a comment at the start of each function to say what it does and to document functions of more than a few lines.

11
e.g. makeList=function(mat,i=2){ #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] } mylist mylist }

12
Calling Conventions for Functions Arguments may be specified in the same order in which they occur in function definition, in which case the values are supplied in order. Arguments may be specified as name=value, when the order in which the arguments appear is irrelevant. 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)

13
Default values When creating a function, the programmer can supply default values. makeList=function(mat,i=2){} means that by default, i=2. The user can change the value when calling the function myRowList=makeList(mymat,1)

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

15
Session: Missing Arguments add <- function(x,y=0){#adds 2 numbers x + y} x + y}add(4) add <- function(x,y){#adds 2 numbers if(missing(y)) x add <- function(x,y){#adds 2 numbers if(missing(y)) x else x+y else x+y} add(4) add(4)

16
Variable Number of Arguments The special argument name “…” in the function definition will match any number of arguments in the call. nargs() returns the number of arguments in the current call.

17
Variable Number of Arguments mean.of.all <- function(…) mean(c(…)) mean.of.all(1:10,20:100,12:14) mean.of.means <- function(…){ means <- numeric() means <- numeric() for(x in list(…)) means <- c(means,mean(x)) for(x in list(…)) means <- c(means,mean(x)) mean(means) mean(means)}

18
Session 2: Variable Number of Arguments mean.of.means <- function(…){ #computes the mean of the means of the # 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)

19
Variables are local Note that any ordinary assignments done within the function are local and temporary and lost after exit from the function. fun1 <- function(){ a <- 1:10 a <- 1:10 rnorm(10) rnorm(10)}a

20
Output from a function The last line of a function should be the output. myfun=function(x){ y=3*x y=3*x y} y}myfun=function(x){ y=3*x y=3*x list(x=x,y=y) list(x=x,y=y) }

21
Editfunname=edit(myfun) brings up an edit window. If funname is the same as myfun, you will save the edited function, overwriting myfun. If you make a syntax error, when editing, R will send you an error message upon closing the edit window and will not save the changes. funname=edit() will bring up the most recent edit window

22
Session 3: Editing a function ?appendappendx=(1:10)*4append(x,3,after=4)myappend=edit(append)myappend(x,3,after=4)

23
Functions calling Functions When a function calls another function, you need to be careful to understand which variables are local to which functions. This is called "scope" and is discussed in the tutorial. (10.7) One of the few differences between Splus and R pertain to "scope" and so it is important to understand this if you are trying to port functions between them.

24
Documenting your Functions You will quickly lose track of all your functions unless you document them. Comments should be added to all functions. If you plan to share the functions, the comments should at least include a list of the function arguments and outputs. You can also create help documents that will respond to ?

25
Creating a Help File R has a mark-up language for creating help files for your functions and other objects. We will look at this for a homework.

Similar presentations

© 2016 SlidePlayer.com Inc.

All rights reserved.

Ads by Google