Introduction to R - Functions, Packages Andrew Jaffe 10/18/10.

Slides:



Advertisements
Similar presentations
Introduction to Programming
Advertisements

2.1 Program Construction In Java
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Introduction to R Brody Sandel. Topics Approaching your analysis Basic structure of R Basic programming Plotting Spatial data.
1 What is JavaScript? JavaScript was designed to add interactivity to HTML pages JavaScript is a scripting language A scripting language is a lightweight.
R for Macroecology Aarhus University, Spring 2011.
Week 5: Loops 1.  Repetition is the ability to do something over and over again  With repetition in the mix, we can solve practically any problem that.
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Executes a statement or statements for a number of times – iteration. Syntax for(initialize; test; increment) { // statements to be executed } Initial.
CIS 101: Computer Programming and Problem Solving Lecture 8 Usman Roshan Department of Computer Science NJIT.
Introduction to Computers and Programming Lecture 4: Mathematical Operators New York University.
Loops Notes adapted from Dr. Flores. It repeats a set of statements while a condition is true. while (condition) { execute these statements; } “while”
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
Programming Introduction November 9 Unit 7. What is Programming? Besides being a huge industry? Programming is the process used to write computer programs.
Programming Epson Robots – Part 2 ME 4135 – Fall 2012 Dr. R. Lindeke.
1 CS428 Web Engineering Lecture 18 Introduction (PHP - I)
1 Introduction to Tool chains. 2 Tool chain for the Sitara Family (but it is true for other ARM based devices as well) A tool chain is a collection of.
Introduction to R - Lecture 4: Looping Andrew Jaffe 9/27/2010.
Python – Part 4 Conditionals and Recursion. Modulus Operator Yields the remainder when first operand is divided by the second. >>>remainder=7%3 >>>print.
1. Know the different types of flow block 2. Understand how problems can be broken down into smaller problems.
IE 212: Computational Methods for Industrial Engineering
Introduction to Python
732A44 Programming in R.  Self-studies of the course book  2 Lectures (1 in the beginning, 1 in the end)  Labs (computer). Compulsory submission of.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 6 Value- Returning Functions and Modules.
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Instructor: Chris Trenkov Hands-on Course Python for Absolute Beginners (Spring 2015) Class #005 (April somthin, 2015)
Hands-on Introduction to R. We live in oceans of data. Computers are essential to record and help analyse it. Competent scientists speak C/C++, Java,
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
Computational Methods of Scientific Programming Lecturers Thomas A Herring, Room , Chris Hill, Room ,
Procedural Programming Criteria: P2 Task: 1.2 Thomas Jazwinski.
Writing Scripts Hadi Otrok COEN 346.
Lecture 2 Conditional Statement. chcslonline.org Conditional Statements in PHP Conditional Statements are used for decision making. Different actions.
Susie’s lecture notes are in the presenter’s notes, below the slides Disclaimer: Susie may have made errors in transcription or understanding. If there.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Counting Loops.
Structured Programming II: If Statements By the end of this class you should be able to: implement branching in a program describe and use an “if” statement.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
The Hashemite University Computer Engineering Department
The Department of Engineering Science The University of Auckland Welcome to ENGGEN 131 Engineering Computation and Software Development Lecture 2 Debugging,
Announcements Assignment 1 due Wednesday at 11:59PM Quiz 1 on Thursday 1.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
BIT 115: Introduction To Programming Professor: Dr. Baba Kofi Weusijana (say Doc-tor Way-oo-see-jah-nah, Doc-tor, or Bah-bah)
CS 101 – Oct. 7 Solving simple problems: create algorithm Structure of solution –Sequence of steps (1,2,3….) –Sometimes we need to make a choice –Sometimes.
National Diploma Unit 4 Introduction to Software Development Procedures and Functions.
 Prepared by: Eng. Maryam Adel Abdel-Hady
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Part 1 Learning Objectives To understand that variables are a temporary named location to store data and that programmers work with different data types.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Python’s Modules Noah Black.
Chapter 2 - Introduction to C Programming
Matlab Training Session 4: Control, Flow and Functions
Topic: Functions – Part 2
Introduction to C++ October 2, 2017.
PHP Introduction.
Chapter 2 - Introduction to C Programming
Repeating code We could repeat code we need more than once: i = 1 print (i) i += 1 print (i) #… stop when i == 9 But each line means an extra line we might.
Engineering Innovation Center
File Handling Programming Guides.
Conditions and Ifs BIS1523 – Lecture 8.
Coding Concepts (Basics)
Repetition Structures
Python 19 Mr. Husch.
Topics Introduction to Value-returning Functions: Generating Random Numbers Writing Your Own Value-Returning Functions The math Module Storing Functions.
Fundamentals of Functional Programming
Vectors and Matrices In MATLAB a vector can be defined as row vector or as a column vector. A vector of length n can be visualized as matrix of size 1xn.
Python 19 Mr. Husch.
Programming The ideal style of programming is Structured or
Presentation transcript:

Introduction to R - Functions, Packages Andrew Jaffe 10/18/10

Overview Functions Packages Questions

Functions Everything you use in R is a built-in function You can download new functions (packages – next section) You can add your own to a script

Functions Built in functions (note the lack of parenthesis – this is also why you don’t want to name variables as functions): > rep function (x,...).Primitive("rep") > c function (..., recursive = FALSE).Primitive("c")

Functions Syntax: functionName <- function(inputs) { body of the function which returns something} You must run/submit the function before you can use it Note that variable naming within a function is protected, and not altered by whatever your script is doing

Functions # tests if a number if positive pos = function(x) { if(x >= 0) out = 1 if(x < 0) out = 0 return(out) } Input Output

Functions > pos = function(x) { + if(x >= 0) out = 1 + if(x < 0) out = 0 + return(out) + } > pos(5) [1] 1 > pos(-5) [1] 0 Run the function first

Functions The value that the function returns can be stored as a new variable > y = pos(4) > y [1] 1

Functions > # protected – x is the # input to pos > x = 3 > pos(6) [1] 1 > x [1] 3

Functions Using return() explicitly tells the function what to return – safe Otherwise, the function will return the last value that it works with or assigns This can be an issue if you use a lot of logical statements

Functions Adding a ‘verbose’ logical variable gives the user some feedback > pos = function(x,verbose=TRUE) { + if(x >= 0) out = 1 + if(x < 0) out = if(verbose) cat("finished running","\n") + return(out) + } > y = pos(5) finished running > y [1] 1

Functions You can change the input into functions when you run them You can name each input, or just put their values in order > y = pos(5, verbose = FALSE) > y = pos(5, FALSE) # same thing > y [1] 1

Functions Here, we set verbose to be TRUE by default, ie that that function says what its doing Using verbose statements throughout your functions makes it easier to use (especially if other people are going to use your function)

Functions Note: really long ‘for’ loops also benefit from using verbose statements %: mod, the remainder of the first number divided by the second Print a period every 10,000 iterations for(i in 1:1e5) { if(i % == 0) cat(".") # do other stuff }

Functions Why do functions? Provides modularity to your code  You can solve small problems using functions  Keeps your actual analysis script cleaner  You can distribute your code script to other people

Functions For example, download the lecture notes, and type source(“lecture_notes.R”) The ‘pos’ function should be added into your working directory Another function, ‘mypar’ was added, but requires a …package!

Functions Make a function that takes two numbers as inputs, and returns their sum Make a function that takes three inputs as inputs and returns their product

Functions summ <- function(a,b) { out = a+b return(out) } prodd <- function(a,b,c) { out = a*b*c return(out) }

Overview Functions Packages Questions

Packages R can access and install a huge library of packages The full list is here: project.org/web/packages/ project.org/web/packages/ You only need to install a package once, then you can use it whenever you want

Packages ?install.packages Let’s try downloading “RColorBrewer” install.packages(“RColorBrewer”) A list of repository directories should pop- up  select USA (basically any of them will work)  I think the Maryland one is Hopkins…

Packages Some installation popups occurs and the package should be installed on your computer Then, library(package_name) library(RColorBrewer) – quotes are optional

Packages ?RColorBrewer: “Creates nice looking color palettes especially for thematic maps” Top left corner: “RColorBrewer {RColorBrewer}“ Top left in mean: “mean {base}” The thing in {} is the package

Packages Now, resource the lecture 7 notes so that the mypar() function gets read in correctly This function will alter the plot parameters to make the color palette more divergent, changes the margin sizes, and can allow you to plot multi-panel plots

Packages mypar() # default is 1 x 1 plot space mypar(2,2) # 2 rows, 2 columns > data(cars) > mypar() > plot(cars, type = "b", col = 5)

Packages I usually google “R + [something I’m trying to do]” and sometimes links can direct you to existing packages The full list is on the CRAN website Some Epi ones are “survival” – survival analysis, “lme4” – longitudinal data analysis, “Epi” – some epi functions

Packages Try installing those packages now Remember, to use a package, you must invoke the library(package) command

Packages library(survival) ?survival ??survival – “fuzzy search” ?Surv

Overview Functions Packages Questions

Questions? Any burning R questions? Open floor…