writing functions -...

40
Writing Functions Part I

Upload: lamdan

Post on 21-Jul-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Writing Functions!!

PartI

In your mat219_class project1.  CreateanewRscriptorRnotebookcalledwri7ng_func7ons2.  Includethiscodeinyourscriptornotebook:

library(tidyverse)library(gapminder)

gapminder <- gapminder::gapminder

checking validity of arguments

Test functions

max_minus_min<-func7on(x){if(!is.numeric(x)){stop(“expectedinputisanumericvector.\n”,“actualinputwasofclass”,class(x)[1])}max(x)–min(x)}

Ifafunc7onwillgetusedagainindifferentcontexts,itisgoodtocheckthevalidityofthearguments

RuleofRepair:Whenyoumustfail,failnoisilyandassoonaspossible

Your Turn 1The max and min of a numeric vector are special cases of a quantile: • min = 0 quantile• Q1 = 0.25 quantile• median = 0.5 quantile• Q3 = 0.75 quantile• max = 1 quantileSuppose we sometimes want max – min, sometime Q3 – Q1 (the IQR), and sometimes the difference between two other quantiles. Write a function that takes the difference of two specified quantiles for a numeric vector. Hint: consider using quantile().

quan7le(gapminder$lifeExp)

quan7le(gapminder$lifeExp,probs=0.5)

median(gapminder$lifeExp)

quan7le(gapminder$lifeExp,probs=c(0.25,0.75))

boxplot(gapminder$lifeExp,plot=FALSE)$stats

takesome7metounderstandhowquan7le()works

the_probs<-c(0.25,0.75)the_quan7les<-quan7le(gapminder$lifeExp,probs=the_probs)max(the_quan7les)-min(the_quan7les)

firststep:getsomethingtowork

secondstep:turnthecodeintoafunc7on

quan7le_diff<-func7on(x,probs){the_quan7les<-quan7le(x=x,probs=probs)max(the_quan7les)-min(the_quan7les)}

IQR(gapminder$lifeExp)

quan7le_diff(gapminder$lifeExp,probs=c(0.25,0.75))

secondstep:turnthecodeintoafunc7on

quan7le_diff<-func7on(x,probs){the_quan7les<-quan7le(x=x,probs=probs)max(the_quan7les)-min(the_quan7les)}

max_minus_min(gapminder$lifeExp)

quan7le_diff(gapminder$lifeExp,probs=c(0,1))

default arguments

max_minus_min(gapminder$lifeExp)

quan7le_diff(gapminder$lifeExp)

itwouldbeniceifourgeneraliza7onworkedthesameasouroldfunc7onwhenwewanteditto

quan7le_diff<-func7on(x,probs=c(0,1)){the_quan7les<-quan7le(x=x,probs=probs)max(the_quan7les)-min(the_quan7les)}

max_minus_min(gapminder$lifeExp)

quan7le_diff(gapminder$lifeExp)

the … argument

?quan7le

quan7le_diff<-func7on(x,probs=c(0,1),…){the_quan7les<-quan7le(x=x,probs=probs,…)max(the_quan7les)-min(the_quan7les)}

quan7le_diff(c(1,2,NA),na.rm=TRUE)

iteration

SetupRun the following code to simulate exam scores for five students:

set.seed(42)stu1 <- runif(10, 50, 100)stu2 <- runif(10, 50, 100)stu3 <- runif(10, 50, 100)stu4 <- runif(10, 50, 100)stu5 <- runif(10, 50, 100)

Task 2For each student, compute the mean exam score after dropping the lowest score. Accomplish this task by writing a function called grade.

Goal:compute the mean exam score after dropping the lowest score.1.  Getsomethingthatworks

(sum(stu1)–min(stu1))/(length(stu1)–1)

Goal:compute the mean exam score after dropping the lowest score.1.  Getsomethingthatworks2.  Turnthatcodeintoafunc7on

grade<-func7on(x){(sum(x)–min(x))/(length(x)–1)}grade(stu1)

grade<-func7on(x){(sum(x)–min(x))/(length(x)–1)}

grade(stu1) grade(stu4)

grade(stu2) grade(stu5)

grade(stu3)

map()

exams<-list(stu1,stu2,stu3,stu4,stu5)map(exams,mean)

Task 3Create a vector of type double that contains the grade (mean after removing the lowest score) for each student.

exams<-list(stu1,stu2,stu3,stu4,stu5)exams%>%map_dbl(grade)

Extra argumentsexams<-list(stu1,stu2,stu3,stu4,stu5)exams%>%map_dbl(quan7le_diff)

Extra argumentsexams<-list(stu1,stu2,stu3,stu4,stu5)exams%>%map_dbl(quan7le_diff,probs=c(0.25,0.75))

operating on a selection of variables

Task 3Write a function that computes the z-score for a numeric vector. Name the function zscore.

zscore<-func7on(x){(x–mean(x))/sd(x)}

gapminder%>%mutate(gdpPercap=zscore(gdpPercap))

gapminder%>%mutate_at(vars(lifeExp:gdpPercap),zscore)

mutate_at()letsyouselectvariablesusingthesamesyntaxastheselect()verb.

gapminder%>%mutate(gdpPercap=zscore(gdpPercap))

gapminder%>%mutate_if(is.numeric,zscore)

mutate_if()letsyouselectvariablesbasedonalogicaltest(calledthepredicate).

Thefollowingdatamanipula7onverbshave*_at(),*_if(),and*_all()variants:• mutate()•  transmute()•  summarise()• filter()•  select()•  rename()•  arrange•  group_by()

dm<-7bble(x=c(34,145,6544,32,129),y=c(345,1452,644,312,6129))dm%>%mutate(z=sqrt(x))

dm<-7bble(x=c(34,145,6544,32,129),y=c(345,1452,644,312,6129))dm%>%mutate(z=reverse_int(x))

reverse_int<-func7on(x){reverse<-0while(x!=0){rem<-x%%10reverse<-reverse*10+remx<-x%/%10}reverse}

dm<-7bble(x=c(34,145,6544,32,129),y=c(345,1452,644,312,6129))dm%>%mutate(z=map_dbl(x,reverse_int))

reverse_int<-func7on(x){reverse<-0while(x!=0){rem<-x%%10reverse<-reverse*10+remx<-x%/%10}reverse}