Example: quiz answers

Introduction to the R Language - Functions

Introduction to the R LanguageFunctionsBiostatistics R LanguageFunctionsFunctions are created using thefunction()directive and arestored as R objects just like anything else. In particular, they are Robjects of class function .f <- function(<arguments>) {## Do something interesting} Functions in R are first class objects , which means that they canbe treated much like any other R object. Importantly, Functions can be passed as arguments to other functionsFunctions can be nested, so that you can define a functioninside of another functionThe return value of a function is the last expression in the functionbody to be R LanguageFunction ArgumentsFunctions havenamed argumentswhich potentially argumentsare the arguments included in thefunction definitionTheformalsfunction returns a list of all the formalarguments of a functionNot every function call in

Argument Matching R functions arguments can be matched positionally or by name. So the following calls to sd are all equivalent > mydata <- rnorm(100)

Tags:

  Introduction, Language, Introduction to the r language

Information

Domain:

Source:

Link to this page:

Please notify us if you found a problem with this document:

Other abuse

Transcription of Introduction to the R Language - Functions

1 Introduction to the R LanguageFunctionsBiostatistics R LanguageFunctionsFunctions are created using thefunction()directive and arestored as R objects just like anything else. In particular, they are Robjects of class function .f <- function(<arguments>) {## Do something interesting} Functions in R are first class objects , which means that they canbe treated much like any other R object. Importantly, Functions can be passed as arguments to other functionsFunctions can be nested, so that you can define a functioninside of another functionThe return value of a function is the last expression in the functionbody to be R LanguageFunction ArgumentsFunctions havenamed argumentswhich potentially argumentsare the arguments included in thefunction definitionTheformalsfunction returns a list of all the formalarguments of a functionNot every function call in R makes use of all the formalargumentsFunction arguments can bemissingor might have defaultvaluesThe R LanguageArgument MatchingR Functions arguments can be matched positionally or by name.

2 Sothe following calls tosdare all equivalent> mydata <- rnorm(100)> sd(mydata)> sd(x = mydata)> sd(x = mydata, = FALSE)> sd( = FALSE, x = mydata)> sd( = FALSE, mydata)Even though it s legal, I don t recommend messing around with theorder of the arguments too much, since it can lead to R LanguageArgument MatchingYou can mix positional matching with matching by name. Whenan argument is matched by name, it is taken out of theargument list and the remaining unnamed arguments are matchedin the order that they are listed in the function definition.> args(lm)function (formula, data, subset, weights, ,method = "qr", model = TRUE, x = FALSE,y = FALSE, qr = TRUE, = TRUE,contrasts = NULL, offset.)

3 The following two calls are (data = mydata, y ~ x, model = FALSE, 1:100)lm(y ~ x, mydata, 1:100, model = FALSE)The R LanguageArgument MatchingMost of the time, named arguments are useful on thecommand line when you have a long argument list and youwant to use the defaults for everything except for an argumentnear the end of the listNamed arguments also help if you can remember the name ofthe argument and not its position on the argument list(plotting is a good example).The R LanguageArgument MatchingFunction arguments can also bepartiallymatched, which is usefulfor interactive work.

4 The order of operations when given anargument is1 Check for exact match for a named argument2 Check for a partial match3 Check for a positional matchThe R LanguageDefining a Functionf <- function(a, b = 1, c = 2, d = NULL) {}In addition to not specifying a default value, you can also set anargument value R LanguageLazy EvaluationArguments to Functions are evaluatedlazily, so they are evaluatedonly as <- function(a, b) {a^2}f(2)This function never actually uses the argumentb, so callingf(2)will not produce an error because the 2 gets positionally R LanguageLazy EvaluationAnother examplef <- function(a, b) {print(a)print(b)}> f(45)[1] 45 Error in print(b) : argument "b" is missing, with no default>Notice that 45 got printed first before the error was is becausebdid not have to be evaluated until afterprint(a).

5 Once the function tried to evaluateprint(b)it had tothrow an R LanguageThe .. indicate a variable number of arguments thatare usually passed on to other often used when extending another function and youdon t want to copy the entire argument list of the originalfunctionmyplot <- function(x, y, type = "l", ..) {plot(x, y, type = type, ..)}Generic Functions that extra arguments can bepassed to methods (more on this later).> meanfunction (x, ..)UseMethod("mean")The R LanguageThe .. is also necessary when the number ofarguments passed to the function cannot be known in advance.

6 > args(paste)function (.., sep = " ", collapse = NULL)> args(cat)function (.., file = "", sep = " ", fill = FALSE,labels = NULL, append = FALSE)The R LanguageArguments Coming After the .. ArgumentOne catch that any arguments that the argument list must be named explicitly and cannot bepartially matched.> args(paste)function (.., sep = " ", collapse = NULL)> paste("a", "b", sep = ":")[1] "a:b"> paste("a", "b", se = ":")[1] "a b :"The R LanguageA Diversion on Binding Values to SymbolHow does R know which value to assign to which symbol? When Itype> lm <- function(x) { x * x }> lmfunction(x) { x * x }how does R know what value to assign to the symbollm?

7 Whydoesn t it give it the value oflmthat is in thestatspackage?The R LanguageA Diversion on Binding Values to SymbolWhen R tries to bind a value to a symbol, it searches through aseries ofenvironmentsto find the appropriate value. When youare working on the command line and need to retrieve the value ofan R object, the order is roughly1 Search the global environment for a symbol name matchingthe one the namespaces of each of the packages on the searchlistThe search list can be found by using thesearchfunction.> search()[1] ".GlobalEnv" "package:stats" "package:graphics"[4] "package:grDevices" "package:utils" "package:datasets"[7] "package:methods" "Autoloads" "package:base"The R LanguageBinding Values to SymbolTheglobal environmentor the user s workspace is always thefirst element of the search list and thebasepackage is alwaysthe order of the packages on the search list matters!

8 User s can configure which packages get loaded on startup soyou cannot assume that there will be a set list of a user loads a package withlibrarythe namespace ofthat package gets put in position 2 of the search list (bydefault) and everything else gets shifted down the that R has separate namespaces for Functions andnon- Functions so it s possible to have an object namedcanda function R LanguageScoping RulesThe scoping rules for R are the main feature that make it differentfrom the original S scoping rules determine how a value is associated with afree variable in a functionR useslexical scopingorstatic scoping.

9 A commonalternative isdynamic to the scoping rules is how R uses thesearch listtobind a value to a symbolLexical scoping turns out to be particularly useful forsimplifying statistical computationsThe R LanguageLexical ScopingConsider the following <- function(x, y) {x^2 + y / z}This function has 2 formal argumentsxandy. In the body of thefunction there is another symbolz. In this casezis called scoping rules of a Language determine how values are assignedto free variables. Free variables are not formal arguments and arenot local variables (assigned insided the function body).

10 The R LanguageLexical ScopingLexical scoping in R means thatthe values of free variables are searched for in theenvironment in which the function was is an environment?Anenvironmentis a collection of (symbol, value) pairs, a symbol be its environment has a parent environment; it is possible foran environment to have multiple children the only environment without a parent is the emptyenvironmentA function + an environment = aclosureorfunction R LanguageLexical ScopingSearching for the value for a free variable:If the value of a symbol is not found in the environment inwhich a function was defined, then the search is continued intheparent search continues down the sequence of parentenvironments until we hit thetop-level environment.


Related search queries