Functions Are Objects
R functions are first-class objects (of the class “function”, of
course), meaning that they can be used for the most part just like other
objects. This is seen in the syntax of function creation:
g <- function(x) {
return(x+1)
}
Here, function() is a built-in R function whose job is to create
functions! On the right-hand side, there are really two arguments to
function(): The first is the formal argument list for the function we’re
creating—here, just x—and the second is the body of that function—here,
just the single statement return(x+1). That second argument must be of
class “expression”. So, the point is that the right-hand side creates a
function object, which is then assigned to g.
These two arguments to function() can later be accessed via the R
functions formals() and body(), as
follows:
formals(g)
$x
body(g)
{
return(x + 1)
}
Recall that when using R in interactive mode, simply typing the name
of an object results in printing that object to the screen. Functions
are no exception, since they are objects just like anything else.
g
function(x) {
return(x+1)
}
Create a function h and simulate a similar case scenario to the one
shown above.
#Enter Answer Here
if you’re using a function that you wrote but which you’ve forgotten
the details of. Printing out a function is also useful if you are not
quite sure what an R library function does. By looking at the code, you
may understand it better. For example, if you are not sure as to the
exact behavior of the graphics function abline(), you could browse
through its code to better understand how to use it.
#Enter Answer Here
LS0tDQp0aXRsZTogIlIgTm90ZWJvb2siDQpvdXRwdXQ6IGh0bWxfbm90ZWJvb2sNCi0tLQ0KDQoNCioqRnVuY3Rpb25zIEFyZSBPYmplY3RzKioNCg0KUiBmdW5jdGlvbnMgYXJlIGZpcnN0LWNsYXNzIG9iamVjdHMgKG9mIHRoZSBjbGFzcyAiZnVuY3Rpb24iLCBvZiBjb3Vyc2UpLCBtZWFuaW5nIHRoYXQgdGhleSBjYW4gYmUgdXNlZCBmb3IgdGhlIG1vc3QgcGFydCBqdXN0IGxpa2Ugb3RoZXIgb2JqZWN0cy4gVGhpcyBpcyBzZWVuIGluIHRoZSBzeW50YXggb2YgZnVuY3Rpb24gY3JlYXRpb246DQoNCmBgYHtyfQ0KZyA8LSBmdW5jdGlvbih4KSB7DQogcmV0dXJuKHgrMSkNCiB9DQpgYGANCg0KDQpIZXJlLCBmdW5jdGlvbigpIGlzIGEgYnVpbHQtaW4gUiBmdW5jdGlvbiB3aG9zZSBqb2IgaXMgdG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