Statistical Programming with R

Similar documents
Statistical Programming with R

Ecffient calculations

Statistics 251: Statistical Methods

BIO5312: R Session 1 An Introduction to R and Descriptive Statistics

a suite of operators for calculations on arrays, in particular

Introduction to R. Stat Statistical Computing - Summer Dr. Junvie Pailden. July 5, Southern Illinois University Edwardsville

R Programming: Worksheet 3

Statistical Programming with R

An introduction to Scheme

Shell programming. Introduction to Operating Systems

Computer Programming: C++

simpler Using R for Introductory Statistics

Statistics 120 Statistical Computing With R. First Prev Next Last Go Back Full Screen Close Quit

Package reval. May 26, 2015

DSCI 325: Handout 24 Introduction to Writing Functions in R Spring 2017

Chapter 6: User defined functions and function files

Functions and Objects. Week 7: Symbolic Computation

Behavior of the sample mean. varx i = σ 2

A Brief Introduction to R

Stochastic Models. Introduction to R. Walt Pohl. February 28, Department of Business Administration

Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

Univariate Data - 2. Numeric Summaries

CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires

CSc 520 Principles of Programming Languages

Variables. Substitution

Lecture 27: Nov 26, S3 Programming. OOP S3 Objects Unpaired (Two Sample) t-test. James Balamuta STAT UIUC

A Brief Introduction to Scheme (II)

R Programming: Worksheet 6

Bjørn Helge Mevik Research Computing Services, USIT, UiO

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 6: User-Defined Functions I

Chapter 15 Functional Programming Languages

R Primer for Introduction to Mathematical Statistics 8th Edition Joseph W. McKean

Statistics 406 Exam November 17, 2005

CS313D: ADVANCED PROGRAMMING LANGUAGE

Lecture 3: Basics of R Programming

What is Matlab? The command line Variables Operators Functions

Fall Semester, Lecture Notes { November 12, Variations on a Scheme Nondeterministic evaluation

Lecture 9 - C Functions

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

mmpf: Monte-Carlo Methods for Prediction Functions by Zachary M. Jones

An Introduction to Statistical Computing in R

Writing Functions! Part I!


Lecture 3: Basics of R Programming

Functional Languages. Hwansoo Han

CS 314 Principles of Programming Languages. Lecture 16

SCHEME AND CALCULATOR 5b

Chapter 1. Fundamentals of Higher Order Programming

An Interactive Desk Calculator. Project P2 of. Common Lisp: An Interactive Approach. Stuart C. Shapiro. Department of Computer Science

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Numeric Vectors STAT 133. Gaston Sanchez. Department of Statistics, UC Berkeley

CS 314 Principles of Programming Languages

Midterm Examination , Fall 2011

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

LECTURE 16. Functional Programming

05R03 Control Structure and Functions

Programming with R. Bjørn-Helge Mevik. RIS Course Week spring Research Infrastructure Services Group, USIT, UiO

An Introduction to Functions

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

INF121: Functional Algorithmic and Programming

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Parsing Scheme (+ (* 2 3) 1) * 1

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

CS111: PROGRAMMING LANGUAGE II

EPIB Four Lecture Overview of R

Programming R. Manuel J. A. Eugster. Chapter 4: Writing your own functions. Last modification on May 15, 2012

User Guide.

Business Statistics: R tutorials

Functional Programming. Big Picture. Design of Programming Languages

Basic Scheme February 8, Compound expressions Rules of evaluation Creating procedures by capturing common patterns

COMP 208 Computers in Engineering

Turtles All The Way Down

CSc 520 Principles of Programming Languages

CS1101: Lecture 9 The Shell as a Programming Language

CSE 341 Section Handout #6 Cheat Sheet

An Introduction to Scheme

Scheme: Strings Scheme: I/O

Functional Programming Lecture 1: Introduction

Chapter 3: Programming with MATLAB

for (i=1; i<=100000; i++) { x = sqrt (y); // square root function cout << x+i << endl; }

MAS115 R programming, Lab Class 5 Prof. P. G. Blackwell

Decaf Language Reference Manual

Lecture 13: Jul 5, Functions. Background Asserting Input Debugging Errors. James Balamuta STAT UIUC

9. Writing Functions

Lecture 3 - Object-oriented programming and statistical programming examples

Prewitt. Gradient. Image. Op. Merging of Small Regions. Curve Approximation. and

Functions of Two Variables

Statistical Programming Worksheet 4

Lecture 7. SchemeList, finish up; Universal Hashing introduction

R Workshop Daniel Fuller

16 Greedy Algorithms

Modeling and Simulating Social Systems with MATLAB

Week 6: Introduction to Programming for GIS and Spatial Data Analysis GEO GEO A

Lecture 02 The Shell and Shell Scripting

Recap: Functions as first-class values

Common LISP Tutorial 1 (Basic)

Appendix A: A Sample R Session

Introduction to Software Testing Chapter 2.3 Graph Coverage for Source Code. Paul Ammann & Jeff Offutt

Transcription:

Statistical Programming with R Lecture 5: Simple Programming Bisher M. Iqelan biqelan@iugaza.edu.ps Department of Mathematics, Faculty of Science, The Islamic University of Gaza 2017-2018, Semester 1

Functions All computations in R are carried out by calling functions. A call to an R function takes zero or more arguments and returns a single value. Dening functions provides users a way of adding new functionality to R. Functions dened by users have the same status as the functions built into R. Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 1 / 18

Dening a function A new function is dened / created by a construct of the form <- function( arglist ) expr where fun.name fun.name is a variable where we store the function. This variable will be used to call the function later arglist is a list of formal arguments. This list can be empty (in which case the function takes no arguments) can have just some names (in which case these names become variables inside the function, whose values have to be supplied when the function is called) can have some arguments in name = value form, in which case the names are variables available inside the function, and the values are their default values expr is an expression (typically an expression block), referred to as the body of a function (which can make use of the variables dened in the argument list). Inside functions, there can be a special return(val) call which exits the function and returns the value val Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 2 / 18

Write an R function To understand the concept of writing a new function in R, consider the following very simple example. cube <- function(number) { result <- number * number * number # or number**3 return(result) cube is the name of the function. function is the R function that creates functions. number is the parameter (name of the value) passed to the cube function. { delimits the beginning of the function delimits the end of the function return is the R function that species what the function returns, in this example, the value of result Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 3 / 18

Writing Function (empty arguments) > fn <- function(){ # A simple function without argument print("hello") > fn() [1] "hello" Another example: By default the value of the last line is returned. Here, we have a simple function with two objects. The last one is returned. > test <- function() { x <-1 z <- 2 > res <- test() > res [1] 2 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 4 / 18

Writing Function (Empty Arguments Continue..) Consider the following very simple example. Here, the arguments are empty > myvalue <- 1 > myfun1 <- function() { myvalue <- 5 print(myvalue) > myfun1() [1] 5 > myvalue [1] 1 > myfun2 <- function() { print(myvalue) > myfun2() [1] 1 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 5 / 18

Writing Function Continue... Let us dene a function which gives the standard deviation of a vector x. We can create this function as follows. > standard.deviation<- function(x){ sqrt(var(x)) > x <- rnorm(100, mean=0, sd=2) > var(x) [1] 3.494888 > standered.deviation(x) [1] 1.869462 > sd(x) [1] 1.869462 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 6 / 18

Function with several arguments Functions can take several arguments. Suppose we want to calculate x 2 + y 2 for inputs of x and y: > f <- function(x, y) { value <- x^2 + y^2 return(value) > f(x = 2, y = 3) [1] 13 It is a good practice to name the arguments (as we did above) when calling a function, but it is not necessary: > f(5, 0) [1] 25 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 7 / 18

Inx functions Most functions in R are prex operators: the name of the function comes before the arguments. You can also create inx functions where the function name comes in between its arguments, like + or -. All user-created inx functions must start and end with %. For example, one could create a new operator that pastes together strings: > `%+%` <- function(x, y) paste(x, y) > "new" %+% " string" [1] "new string" > `%+%`("new", " string") [1] "new string" Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 8 / 18

Example 1 Hence, to obtain the standard.deviation notice that we used two existing functions, the sqrt() and var(). This is a fundamental idea when there is need for dening a new function in R. This example shows how we can use the for and the if function to get the sign of a real number. > new.sign <- function(x) { for (i in 1:length(x)) { x > new.sign(-10:5) if(x[i] > 0) x[i] <- 1 else if(x[i] < 0) x[i] <- -1 [1] -1-1 -1-1 -1-1 -1-1 -1-1 0 1 1 1 1 1 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 9 / 18

Example Continue... However a better way is the following which avoids iterations. > sgnfunction <- function(x) { ifelse(x > 0, 1, ifelse(x<0, -1, 0)) > sgnfunction(-10:5) [1] -1-1 -1-1 -1-1 -1-1 -1-1 0 1 1 1 1 1 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 10 / 18

Example 2 Consider the following function using if statement: > iffun=function(x){ if (x==2){ print ("x=2") else { print ("x!=2") > iffun(1) [1] "x!=2" > iffun(2) [1] [1] "x=2" Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 11 / 18

Example 2 Cont... > iffun2=function(x){ ifelse(x==2, "x=2", "x!=2") > iffun2(1) [1] "x!=2" > iffun2(2) [1] [1] "x=2" Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 12 / 18

args() and body() functions In R, args() and body() give the two components of a function: > args(new.sign) function (x) NULL > body(new.sign) { for (i in 1:length(x)) { if (x[i] > 0) x[i] <- 1 else if (x[i] < 0) x[i] <- -1 x Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 13 / 18

A function returning a vector Suppose we want to create a function which summarizes a numerical variable in a few statistical terms (mean, variance etc) and returns a vector with these terms. This can be done with > mysummary <- function(x) { value <- c(mean(x), median(x), var(x), min(x), max(x)) return(value) > mysummary(-10:20) [1] 5.00000 5.00000 82.66667-10.00000 20.00000 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 14 / 18

A function returning a vector Continue... The output of this function is not directly readable (unless we investigate how mysummary was dened). A much more informative output can be obtained by naming the components of the output vector: > mysummary <- function(x) { value <- c(mean = mean(x), med = median(x), var = var(x),min = min(x), max = max(x)) return(value) > mysummary(-10:20) mean med var min max 5.00000 5.00000 82.66667-10.00000 20.00000 Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 15 / 18

A function returning a list A function can also return a list. For example: > mysummary <- function(x) { value <- list(mean = mean(x), med = median(x), var = var(x), min = min(x), max = max(x)) return(value) > (v <- mysummary(cars$speed)) $mean [1] 15.4 $med [1] 15 $var [1] 27.95918 $min [1] 4 $max [1] Bisher M. 25Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 16 / 18

Example: Multiple of a number Example, a vector x containing the rst 100 multiples of the number k. > multiple=function(k){ x=0 for(i in 1:100) { x[i]=k*i x # This last entry is the output from the function. # The function only outputs the last line. To run the programs, type multiple(6). This gives the rst 100 multiples of 6. Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 17 / 18

Example: Tossing a coin Write a function to simulate a coin toss which allows the user to set p, the probability that the coin shows a head. coin=function(p) { u=runif(1) # Shorthand for U(0,1). if(u<=p) coin="head" if(u>p) coin="tail" coin # This is the output from the program. To run the programs, assuming a fair coin, type coin(0.5). Bisher M. Iqelan (IUG) Lecture 5: Simple Programming 1 st Semester 2017 18 / 18

End of lecture 5. Thank you.!!!