44
Basic Concepts in Programming/ Introduc5on to R Jan 9‐10, 2012 Instructor: Wing‐Yee Chow WinterStorm 2012

Basic Concepts in Programming/ Introducon to Rling.umd.edu/~wychow/Wing_Yee_Chow/teaching/Intro_R_Programming...Basic Concepts in Programming/ Introducon to R Jan 9‐10, 2012 Instructor:

  • Upload
    lenga

  • View
    220

  • Download
    3

Embed Size (px)

Citation preview

BasicConceptsinProgramming/Introduc5ontoR

Jan9‐10,2012Instructor:Wing‐YeeChow

WinterStorm2012

BasicWorkflow

•  Characterizetheproblem

•  Spelloutthestepstowardssolvingtheproblem

•  Materializethestepsinaprogramminglanguage

•  Testanddebug

WinterStorm2012

BasicTerminology

•  variables•  types•  vectors•  indices•  operators•  func5ons•  condi5onals•  loops•  input/output

WinterStorm2012

Variables

•  Placeholdersforvalues–  InR,youcanassignvaluestoavariableusing“<‐”

WinterStorm2012

> a <- 5 > b <- 4 > a + b [1] 9 > c <- a*b > c [1] 20

VariableNamesinR

•  Case‐sensi5ve,soxisnotthesameasX.•  Mustnotbeginwithnumbers(e.g.1x)orsymbols(e.g.%x).

•  Mustnotcontainblankspacesoroperatorsymbols:– usesubject.list orsubject_listbutnotsubject listorsubject-list

WinterStorm2012

•  Differenttypesdifferentopera5ons–  InR,themostimportanttypesarenumbersandstrings.

Types

WinterStorm2012

> a <- 5 # number > b <- “Hello” # string > c <- 1<2 > c [1] TRUE # logical

•  InR,thebasicvaluesarevectors.

Vectors

WinterStorm2012

a <- c(1,2,5.3,6,-2,4) # numeric vector

b <- c(”apples”,”books”,”cats”) # character vector

c <- c(TRUE,TRUE,TRUE,FALSE,TRUE,FALSE) # logical vector

•  Addresspar5cularmembersofanobject–  InR,usesquarebrackets[]forindices,androundbrackets()forfunc5ons,e.g.,length()

–  InR,thefirstelementinavectorhastheindex1.Thus,theindexofthelastelementisthelengthofthevector.

Indices

WinterStorm2012

> a <- c(37,42,89) > a[1] [1] 37 > length(a) [1] 3 > a[length(a)] [1] 89

•  Youcanaddressthesamethingsindifferentways–  Indicescanbeavectorofintegersorlogicalvalues.(Wewillexpandon

thiswhenwedealwithdataframes)

Indices

WinterStorm2012

> a <- c(37,42,89) > a[1:2] [1] 37 42 > a[c(1,3)] [1] 37 89 > a[c(TRUE, FALSE, FALSE)] [1] 37 > a[a>40] # where a>40 returns [1] 42 89 # FALSE TRUE TRUE

•  Programminglanguage‐dependent•  CommonoperatorsinR:

Operators

WinterStorm2012

+ - * / %% ^ arithme5c

> >= < <= == != rela5onal

! & | logical

~ modelformulae

<- -> assignment

$ listindexing(the‘elementname’operator)

: createasequence

Exercise1

•  UseRtofindallthenumbersbetween1and2000whicharemul5plesof317.

•  Youwillneedtheoperators:and%%

WinterStorm2012

> 1:5 [1] 1 2 3 4 5 > 18 %% 5 [1] 3 > 4 %% 2 [1] 0

Exercise1

•  UseRtofindallthenumbersbetween1and2000whicharemul5plesof317.

•  Solu5on:

•  Follow‐up:UseRtofindouthowmanynumbersbetween1and2000aremul5plesof17.

WinterStorm2012

> a <- 1:2000 > a[ a%%317 ==0] [1] 317 634 951 1268 1585 1902

Exercise2

•  Findallthewordswithlessthan6ormorethan8charactersinthevectorc("Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana”).

•  YouwillneedtheORoperator|andfunc5onnchar()

WinterStorm2012

> a <- "Maryland" > nchar(a) [1] 8

Exercise2

•  Findallthewordswithlessthan6ormorethan8charactersinthegivenvector.

•  Solu5on:

•  Follow‐up:Modifythisfunc5ontoshowthenumberofcharactersofthereturnedvalues.

WinterStorm2012

> a<- c("Maine", "Maryland", "Massachusetts", "Michigan", "Minnesota", "Mississippi", "Missouri", "Montana") > a[nchar(a)>8 | nchar(a)<6] [1] "Maine" "Massachusetts" "Minnesota" "Mississippi"

•  Rhasawiderangeofbuilt‐infunc5ons.

Func5ons

WinterStorm2012

length(c(4,2,9)) [1] 3 max(c(1,2,4,2,5,-1,1)) [1] 5 sum(c(1,2,3,4)) [1] 10 mean(c(0.5, 3.4, 8.9, 4,4, 6.7)) [1] 4.583333 sd(c(0.5, 3.4, 8.9, 4,4, 6.7)) [1] 2.893729

•  Usehelp()tolookupfunc5ons•  Youcanalsowriteyourownfunc5ons

•  Localvs.globalvariables

Func5ons

WinterStorm2012

> myfunction <- function(x,y){ + z <- x + y^2 + return(z) + } > answer <- myfunction(3,4) > answer [1] 19

Pleasedownloadthenewslidesandexercises

WinterStorm2012

Func5ons

WinterStorm2012

myfunction <- function(x,y){ z <- x + y^2 return(z) }

Function name

> inputA <- 3 > inputB <- 4 > answer <- myfunction(inputA,inputB) > answer [1] 19

Calling/Usingyourfunc5on

Crea5ngafunc5onArgument(s) taken by this function

Do computations with the argument(s) [You can also refer to global variables, but be very careful]

Output of the function

You can use global variables as the input to a function

Global variables

Local variables

Call your function

Exercise3

•  Writeafunc5onthatreturnstheproductoftheminimumandmaximumoftheinputvector.

•  Youwillneedmax()andmin().

WinterStorm2012

Exercise3

•  Writeafunc5onthatreturnstheproductoftheminimumandmaximumoftheinputvector.

•  Solu5on:

•  Follow‐up:Modifythisfunc5ontoconsiderthemaximumandminimumoftheabsolutevalueoftheinputvector.[Hint:useabs()]

WinterStorm2012

exercise3 <- function(x){ product <- max(x)* min(x) return(product) }

> exercise3(c(7,-3,2,30)) [1] -90

Test your function

Exercise4

•  Writeafunc5onthatconvertstemperaturesfromCelsiustoFahrenheit.

•  [°F]=9⁄5[°C]+32

WinterStorm2012

Exercise4

•  Writeafunc5onthatconvertstemperaturesfromCelsiustoFahrenheit,where[°F]=9⁄5[°C]+32.

•  Solu5on:

•  Follow‐up:Writeafunc5onthatconvertsfromFahrenheittoCelsius.

WinterStorm2012

exercise4.c2f <- function(celsius){ fahreheit <- (celsius*9/5)+32 return(fahreheit) }

> exercise4.c2f(20) [1] 68

Test your function

Exercise5

•  Writeafunc5onthatfindsallthenumberswithinavectorxthataremul5plesofanintegery.[ageneralversionofEx.1]

WinterStorm2012

Exercise5

•  Writeafunc5onthatfindsallthenumberswithinavectorxthataremul5plesofanintegery.[ageneralversionofEx.1]

•  Solu5on:

WinterStorm2012

exercise5 <- function(x,y){ z<- x[(x%%y)==0] return(z) }

> ans5 <- exercise5(1:2000,317)

•  Carryoutanopera5onwhenacondi5onissa5sfied,e.g.,ifAistruethendoB,otherwisedoC(ornothing)

•  Example(findingtheabsolutevalueofaninputwithoutusingabs()):

•  Quickexercise:trytoinputavectorandseehowthesetwofunc5onsdiffer

Condi5onals

WinterStorm2012

> ifelse(x<0,-x,x) > if (x<0) {-x} else {x}

•  Compareifelseandif:

Condi5onals

WinterStorm2012

abs.ifelse <- function(x){ result <- ifelse(x<0,-x,x) return(result) }

> a <- -10 > abs.ifelse(a) [1] 10 > > b <- c(2,3,-4) > abs.ifelse(b) [1] 2 3 4

Test your function

•  Compareifelseandif:

Condi5onals

WinterStorm2012

abs.if <- function(x){ if (x<0) {result <- -x} else {result <- x} return(result) }

> a <- -10 > abs.if(a) [1] 10 > b <- c(2,3,-4) > abs.if(b) [1] 2 3 -4 Warning message: In if (x < 0) { : the condition has length > 1 and only the first element will be used

Test your function

•  ifelseevaluateseachelementinturn.– Goodforserngvaluesofvariablesbasedonavectoroflogicalcondi5ons

– e.g.,takingtheabsolutevalueofavector•  ifevaluatesonlythefirstelement.Allotherelementsareignored.– Usethisforflowcontrol–toexecuteoneormorestatementsbasedonacondi8on

Condi5onals

WinterStorm2012

Exercise6

•  Writeafunc5onthattakestwoarguments,xandy,andoutputsamessageaboutwhetherxexistsiny.

•  Youwillneedtheoperator%in%.

•  Op5onal:Youmightalsoneedcat().

WinterStorm2012

> content<- c("D2","V4","B6","N5","F3") > "N5" %in% content [1] TRUE > "N4" %in% content [1] FALSE

> a <- "apple" > b <- "tree" > cat(a,b) apple tree

Exercise6

•  Writeafunc5onthattakestwoarguments,xandy,andoutputsamessageaboutwhetherxexistsiny.

•  Solu5on:

WinterStorm2012

exercise6 <- function(x,y){ if (x %in% y) { cat(x,"exists in",y) } else { cat(x,"does not exist in",y) } }

> target <- c("D2") > content <- c("C1","B4","D2","F5") > exercise6(target, content) D2 exists in C1 B4 D2 F5

•  For‐loops–  repeatanac5onforapredeterminednumberof5mes

–  thevalueofthelocalvariablechangesineachitera5on

Loops

WinterStorm2012

> for (i in 3:5){ + print(i) + } [1] 3 [1] 4 [1] 5

Foreachelementinthisvectorthelocalvariableissettothevalueofthatelementandthestatementsintheloopareevaluated.

•  For‐loops– anotherexample:

Loops

WinterStorm2012

> x <- c("Happy","New","Year") > for (i in x) {print(i)} [1] "Happy" [1] "New" [1] "Year" > for (i in x[2:length(x)]) {print(i)} [1] "New" [1] "Year"

•  For‐loops– Whatisthedifference?

Loops

WinterStorm2012

> x <- c("Happy","New","Year") > for (i in x[2:length(x)]) {print(i)} [1] "New" [1] "Year”

> for (i in 2:length(x)) {print(x[i])} [1] "New" [1] "Year"

Exercise7

•  Usingafor‐loop,writeafunc5onthatprintseachofthevaluesinavector,followedby“Even”ifitisdivisibleby2and“Odd”otherwise.

•  Youcanusecat()todisplaythenumberandthestringtogether

WinterStorm2012

> a<- "R Course" > cat(a, "Day 2") R Course Day 2

Exercise7

•  Usingafor‐loop,writeafunc5onthatprintseachofthevaluesinavector,followedby“Even”ifitisdivisibleby2and“Odd”otherwise.

•  Solu5on:

WinterStorm2012

> exercise7 <- function(x){ + for (i in x){ + if (i%%2==0) {result <- "Even” + } else {result <- "Odd”} + cat(i,result,"\n") + } + } > exercise7(c(95,46)) 95 Odd 46 Even

“\n” is a line break

Exercise7

•  Follow‐up:modifythisfunc5ontoprint“Notaninteger”(insteadof“Odd”)ifavalueisnotaninteger[Hint:youcanuse%%todetermineisanumberisaninteger]

WinterStorm2012

Exercise8

•  Usingtwofor‐loops,print1instanceof“Apples” followedby4instancesof“Oranges”,anddothis35mes.

WinterStorm2012

Exercise8

•  Usingtwofor‐loops,print1instanceof“Apples” followedby4instancesof“Oranges”,anddothis35mes.

•  Solu5on:

•  Follow‐up:Makethisafunc5onthatcandothesameac5ontodifferentwordpairs.

WinterStorm2012

for (i in 1:3){ print ("Apples") for (j in 1:4){ print ("Oranges") } }

Exercise8

•  Follow‐up:Makethisafunc5onthatcandothesameac5ontodifferentwordpairs.

WinterStorm2012

exercise8 <- function(word1,word2){ for (i in 1:3){ print (word1) for (j in 1:4){ print (word2) } } }

> exercise8("Apples","Oranges")

•  While‐loops– similartofor‐loops,executesomecodesrepeatedlyun5lacondi5onissa5sfied

Loops

WinterStorm2012

> i <- 1 > while (i <= 3) { + print(i) + i <- i + 1 + } [1] 1 [1] 2 [1] 3

Exercise9

•  Usingawhile‐loop,writeafunc5onthatcomputesthesumofthevaluesinavector.[Callitmy_sum().ThisshouldgivethesameresultasR’sbuilt‐insum()func5on.]

WinterStorm2012

Exercise9

•  Usingawhile‐loop,writeafunc5onthatcomputesthesumofthevaluesinavector.

•  Solu5on:

WinterStorm2012

my_sum <- function(x){ i <- 1 temp.sum <- 0 while (i <= length(x)) { temp.sum <- temp.sum + x[i] i <- i + 1 } return(temp.sum) }

Exercise10

•  Usingawhile‐loop,computethefactorialof53.[Thisshouldgivethesameresultasfactorial(53).]

•  Follow‐up:Makethisafunc5on.[Callitmy_factorial()]

WinterStorm2012

Exercise10

•  Follow‐up:Makethisafunc5onthatcomputesthefactorialofaninput.[Callitmy_factorial()]

•  Solu5on:

WinterStorm2012

my_factorial <- function (x) { fac <- 1 while (x > 0) { fac <- fac * x x <- x - 1 } return(fac) }