-
Notifications
You must be signed in to change notification settings - Fork 39
03: Functions
What function allows you to tell if an object is a function? What function allows you to tell if a function is a primitive function?
is.function
, is.primitive
objs <- mget(ls("package:base"), inherits = TRUE)
funs <- Filter(is.function, objs)
Alathea:
The arguments can be obtained using the function formals
.
require(plyr)
# create a vector of lengths
arg_length <- lapply(funs, function(x)(length(formals(x))))
# find the max
max_args <- which(arg_length == max(unlist((arg_length)))
# get the name of the function
names(funs[max_args])
The function is scan()
Alathea:
Continuing from the code above:
length(which(arg_length == 0))
Alathea:
prims <- Filter(is.primitive, objs)
names(prims)
formals()
: the arguments
body()
: the function content
environment()
: the environment where the variables are stored
If the function has a custom print method, or if it is a primitive function.
c <- 10
c(c = c)
The first c()
runs the combine function to create a vector with an item named c
with value 10
name masking, functions vs. variables, a fresh start, dynamic lookup
f <- function(x) {
f <- function(x) {
f <- function(x) {
x ^ 2
}
f(x) + 1
}
f(x) * 2
}
f(10)
Alathea:
The function will go down to the lowest level and find x ^ 2
so f(x) <- 100
. Next, R will arrive at the command f(x) + 1
and get 100 + 1 = 101
and finally multiply by two to get 202
x <- sample(c(1:10, NA), 20, replace = TRUE)
y <- runif(20, 0, 1)
cor(x, y, use = "pairwise", method = "kendall")
f1 <- function(x = {y <- 1; 2}, y = 0) {
x + y
}
f1()
f2 <- function(x = z) {
z <- 100
x
}
f2()
Create a list of all the replacement functions found in the base package. Which ones are primitive functions?
Anything surrounded in %%
e.g. %my_function%
Alathea:
%xor%
<- function(x, y)
{
xor(x, y)
}
Alathea:
`%=%` <- function(x, y)
{
intersect(x, y)
}
`%+%` <- function(x, y)
{
union(x, y)
}
`%-%` <- function(x, y)
{
setdiff(x, y)
}
How does the chdir parameter of source()
compare to in_dir()
? Why might you prefer one approach to the other?
What function undoes the action of library()
? How do you save and restore the values of options()
and par()
?
Alathea:
detach
will remove the library.
options()
and par()
work the same weird way as setwd()
. You can save them while also changing them. So old <- options(newopts)
will actually save the old options while also setting the new ones.
Write a function that opens a graphics device, runs the supplied code, and closes the graphics device (always, regardless of whether or not the plotting code worked).
Alathea:
plotter <- function()
{
x <- seq(1:10)
y <- runif(10)
plot(x, y)
on.exit(dev.off())
}
capture.output2 <- function(code) {
temp <- tempfile()
on.exit(file.remove(temp), add = TRUE)
sink(temp)
on.exit(sink(), add = TRUE)
force(code)
readLines(temp)
}
capture.output2(cat("a", "b", "c", sep = "\n"))
#> [1] "a" "b" "c"