# 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

• View
217

3

Embed Size (px)

### Text of Basic Concepts in Programming/ Introducon to...

• BasicConceptsinProgramming/Introduc5ontoR

Jan910,2012Instructor:WingYeeChow

WinterStorm2012

• BasicWorkflow

Characterizetheproblem Spelloutthestepstowardssolvingtheproblem Materializethestepsinaprogramminglanguage Testanddebug

WinterStorm2012

• BasicTerminology

variables types vectors indices operators func5ons condi5onals loops input/output

WinterStorm2012

• Variables

Placeholdersforvalues InR,youcanassignvaluestoavariableusing a b a + b [1] 9 > c c [1] 20

• VariableNamesinR

Casesensi5ve,soxisnotthesameasX. Mustnotbeginwithnumbers(e.g.1x)orsymbols(e.g.%x).

Mustnotcontainblankspacesoroperatorsymbols:usesubject.list orsubject_listbutnotsubject listorsubject-list

WinterStorm2012

• Differenttypesdifferentopera5ons InR,themostimportanttypesarenumbersandstrings.

Types

WinterStorm2012

> a b c

• InR,thebasicvaluesarevectors.

Vectors

WinterStorm2012

a

InR,thefirstelementinavectorhastheindex1.Thus,theindexofthelastelementisthelengthofthevector.

Indices

WinterStorm2012

> a a[1] [1] 37 > length(a) [1] 3 > a[length(a)] [1] 89

thiswhenwedealwithdataframes)

Indices

WinterStorm2012

> a 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

• Programminglanguagedependent CommonoperatorsinR:

Operators

WinterStorm2012

+ - * / %% ^ arithme5c

> >= <

• Exercise1

UseRtofindallthenumbersbetween1and2000whicharemul5plesof317.

Youwillneedtheoperators:and%%

WinterStorm2012

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

• Exercise1

UseRtofindallthenumbersbetween1and2000whicharemul5plesof317.

Solu5on:

Followup:UseRtofindouthowmanynumbersbetween1and2000aremul5plesof17.

WinterStorm2012

> a 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 nchar(a) [1] 8

• Exercise2

Findallthewordswithlessthan6ormorethan8charactersinthegivenvector.

Solu5on:

Followup:Modifythisfunc5ontoshowthenumberofcharactersofthereturnedvalues.

WinterStorm2012

> a a[nchar(a)>8 | nchar(a)

• Rhasawiderangeofbuiltinfunc5ons.

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

WinterStorm2012

• Func5ons

WinterStorm2012

myfunction

• Exercise3

Writeafunc5onthatreturnstheproductoftheminimumandmaximumoftheinputvector.

Youwillneedmax()andmin().

WinterStorm2012

• Exercise3

Writeafunc5onthatreturnstheproductoftheminimumandmaximumoftheinputvector.

Solu5on:

Followup:Modifythisfunc5ontoconsiderthemaximumandminimumoftheabsolutevalueoftheinputvector.[Hint:useabs()]

WinterStorm2012

exercise3

• Exercise4

Writeafunc5onthatconvertstemperaturesfromCelsiustoFahrenheit.

[F]=95[C]+32

WinterStorm2012

• Exercise4

Writeafunc5onthatconvertstemperaturesfromCelsiustoFahrenheit,where[F]=95[C]+32.

Solu5on:

Followup:Writeafunc5onthatconvertsfromFahrenheittoCelsius.

WinterStorm2012

exercise4.c2f

• Exercise5

Writeafunc5onthatfindsallthenumberswithinavectorxthataremul5plesofanintegery.[ageneralversionofEx.1]

WinterStorm2012

• Exercise5

Writeafunc5onthatfindsallthenumberswithinavectorxthataremul5plesofanintegery.[ageneralversionofEx.1]

Solu5on:

WinterStorm2012

exercise5

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

Example(findingtheabsolutevalueofaninputwithoutusingabs()):

Quickexercise:trytoinputavectorandseehowthesetwofunc5onsdiffer

Condi5onals

WinterStorm2012

> ifelse(x if (x

• Compareifelseandif:

Condi5onals

WinterStorm2012

abs.ifelse b abs.ifelse(b) [1] 2 3 4

• Compareifelseandif:

Condi5onals

WinterStorm2012

abs.if

• ifelseevaluateseachelementinturn.Goodforserngvaluesofvariablesbasedonavectoroflogicalcondi5ons

e.g.,takingtheabsolutevalueofavector ifevaluatesonlythefirstelement.Allotherelementsareignored.Usethisforflowcontroltoexecuteoneormorestatementsbasedonacondi8on

Condi5onals

WinterStorm2012

• Exercise6

Youwillneedtheoperator%in%.

Op5onal:Youmightalsoneedcat().

WinterStorm2012

> content "N5" %in% content [1] TRUE > "N4" %in% content [1] FALSE

> a b cat(a,b) apple tree

• Exercise6

Solu5on:

WinterStorm2012

exercise6 target content exercise6(target, content) D2 exists in C1 B4 D2 F5

• Forloops repeatanac5onforapredeterminednumberof5mes thevalueofthelocalvariablechangesineachitera5on

Loops

WinterStorm2012

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

Foreachelementinthisvectorthelocalvariableissettothevalueofthatelementandthestatementsintheloopareevaluated.

• Forloopsanotherexample:

Loops

WinterStorm2012

> x 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"

• ForloopsWhatisthedifference?

Loops

WinterStorm2012

> x 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

Usingaforloop,writeafunc5onthatprintseachofthevaluesinavector,followedbyEvenifitisdivisibleby2andOddotherwise.

Youcanusecat()todisplaythenumberandthestringtogether

WinterStorm2012

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

• Exercise7

Usingaforloop,writeafunc5onthatprintseachofthevaluesinavector,followedbyEvenifitisdivisibleby2andOddotherwise.

Solu5on:

WinterStorm2012

> exercise7

• Exercise7

WinterStorm2012

• Exercise8

Usingtwoforloops,print1instanceofApples followedby4instancesofOranges,anddothis35mes.

WinterStorm2012

• Exercise8

Usingtwoforloops,print1instanceofApples followedby4instancesofOranges,anddothis35mes.

Solu5on:

Followup:Makethisafunc5onthatcandothesameac5ontodifferentwordpairs.

WinterStorm2012

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

• Exercise8

Followup:Makethisafunc5onthatcandothesameac5ontodifferentwordpairs.

WinterStorm2012

exercise8 exercise8("Apples","Oranges")

• Whileloopssimilartoforloops,executesomecodesrepeatedlyun5lacondi5onissa5sfied

Loops

WinterStorm2012

> i while (i

• Exercise9

Usingawhileloop,writeafunc5onthatcomputesthesumofthevaluesinavector.[Callitmy_sum().ThisshouldgivethesameresultasRsbuiltinsum()func5on.]

WinterStorm2012

• Exercise9

Usingawhileloop,writeafunc5onthatcomputesthesumofthevaluesinavector.

Solu5on:

WinterStorm2012

my_sum

• Exercise10

Usingawhileloop,computethefactorialof53.[Thisshouldgivethesameresultasfactorial(53).]

Followup:Makethisafunc5on.[Callitmy_factorial()]

WinterStorm2012

• Exercise10

Followup:Makethisafunc5onthatcomputesthefactorialofaninput.[Callitmy_factorial()]

Solu5on:

WinterStorm2012

my_factorial

Documents
Documents
Technology
Documents
Documents
Documents
Education
Documents
Documents
Documents
Documents
Documents