This report is automatically generated with the R package knitr (version 1.5) .

# Chapter 8 Putting the Fun in Functions Moving from Scripts to Functions Making the script
x <- c(0.458, 1.6653, 0.83112)
percent <- round(x * 100, digits = 1)
result <- paste(percent, "%", sep = "")
print(result)
## [1] "45.8%"  "166.5%" "83.1%"
# source('pastePercent.R') # Only after saving Transforming the script
addPercent <- function(x) {
    percent <- round(x * 100, digits = 1)
    result <- paste(percent, "%", sep = "")
    return(result)
}
## Using the function
ls()
## [1] "addPercent" "percent"    "result"     "x"
### Formatting the numbers
new.numbers <- c(0.8223, 0.02487, 1.62, 0.4)
addPercent(new.numbers)
## [1] "82.2%" "2.5%"  "162%"  "40%"
### Playing with function objects
ppaste <- addPercent
ppaste
## function(x) {
##     percent <- round(x * 100, digits = 1)
##     result <- paste(percent, "%", sep = "")
##     return(result)
## }
## 
## Reducing the number of lines Returning values by default AddPercent function without last
## return - not written in book
addPercent <- function(x) {
    percent <- round(x * 100, digits = 1)
    result <- paste(percent, "%", sep = "")
}
print(addPercent(new.numbers))
## [1] "82.2%" "2.5%"  "162%"  "40%"
addPercent <- function(x) {
    percent <- round(x * 100, digits = 1)
    paste(percent, "%", sep = "")
}
addPercent <- function(x) {
    if (!is.numeric(x))
        return(NULL)
    percent <- round(x * 100, digits = 1)
    paste(percent, "%", sep = "")
}
### Breaking the walls
odds <- function(x) x/(1 - x)
odds(0.8)
## [1] 4
addPercent <- function(x) paste(round(x * 100, digits = 1), "%", sep = "")
# Using Arguments the Smart Way Adding more arguments
percentages <- c(58.23, 120.4, 33)
addPercent(percentages/100)
## [1] "58.2%"  "120.4%" "33%"
### Adding the mult argument
addPercent <- function(x, mult) {
    percent <- round(x * mult, digits = 1)
    paste(percent, "%", sep = "")
}
addPercent(percentages, mult = 1)
## [1] "58.2%"  "120.4%" "33%"
### Adding a default value addPercent(new.numbers) # Gives error for illustrative purposes
### Error in x * mult : 'mult' is missing
addPercent <- function(x, mult = 100) {
    percent <- round(x * mult, digits = 1)
    paste(percent, "%", sep = "")
}
addPercent(new.numbers)
## [1] "82.2%" "2.5%"  "162%"  "40%"
addPercent(percentages, 1)
## [1] "58.2%"  "120.4%" "33%"
## Conjuring tricks with dots
addPercent <- function(x, mult = 100, ...) {
    percent <- round(x * mult, ...)
    paste(percent, "%", sep = "")
}
addPercent(new.numbers, digits = 2)
## [1] "82.23%" "2.49%"  "162%"   "40%"
addPercent(new.numbers)
## [1] "82%"  "2%"   "162%" "40%"
addPercent <- function(x, mult = 100, digits = 1) {
    percent <- round(x * mult, digits = digits)
    paste(percent, "%", sep = "")
}
## Using functions as arguments Applying different ways of rounding
addPercent <- function(x, mult = 100, FUN = round, ...) {
    percent <- FUN(x * mult, ...)
    paste(percent, "%", sep = "")
}
addPercent(new.numbers, FUN = signif, digits = 3)
## [1] "82.2%" "2.49%" "162%"  "40%"
### Using anonymous functions
profits <- c(2100, 1430, 3580, 5230)
rel.profit <- function(x) round(x/sum(x) * 100)
addPercent(profits, FUN = function(x) round(x/sum(x) * 100))
## [1] "17%" "12%" "29%" "42%"
addPercent(profits/sum(profits))
## [1] "17%" "12%" "29%" "42%"
# Coping with Scoping Crossing the borders Creating a test case
x <- 1:5
test <- function(x) {
    cat("This is x:", x, "\n")
    rm(x)
    cat("This is x after removing it:", x, "\n")
}
test(5:1)
## This is x: 5 4 3 2 1 
## This is x after removing it: 1 2 3 4 5
### Searching the path Using internal functions
calculate.eff <- function(x, y, control) {
    min.base <- function(z) z - mean(control)
    min.base(x)/min.base(y)
}
half <- c(2.23, 3.23, 1.48)
full <- c(4.85, 4.95, 4.12)
nothing <- c(0.14, 0.18, 0.56, 0.23)
calculate.eff(half, full, nothing)
## [1] 0.4270 0.6319 0.3129
# Dispatching to a Method Finding the methods behind the function
print
## function (x, ...) 
## UseMethod("print")
## 
## 
### Using methods with UseMethod
small.one <- data.frame(a = 1:2, b = 2:1)
print.data.frame(small.one)
##   a b
## 1 1 2
## 2 2 1
### Using default methods
print.default(small.one)
## $a
## [1] 1 2
## 
## $b
## [1] 2 1
## 
## attr(,"class")
## [1] "data.frame"
## Doing it yourself Adapting the addPercent function
addPercent.character <- function(x) {
    paste(x, "%", sep = "")
}
# Not written out in the book - needed for rest code #
addPercent.numeric <- function(x, mult = 100, FUN = round, ...) {
    percent <- FUN(x * mult, ...)
    paste(percent, "%", sep = "")
}
addPercent <- function(x, ...) {
    UseMethod("addPercent")
}
addPercent(new.numbers, FUN = floor)
## [1] "82%"  "2%"   "162%" "40%"
addPercent(letters[1:6])
## [1] "a%" "b%" "c%" "d%" "e%" "f%"
# Adding a default function addPercent(small.one) # Gives error on purpose Error in
# UseMethod('addPercent') : no applicable method for 'addPercent' applied to an object of
# class 'data.frame'
addPercent.default <- function(x) {
    cat("You should try a numeric or character vector.\n")
}

The R session information (including the OS info, R version and all packages used):

sessionInfo()
## R version 3.0.2 (2013-09-25)
## Platform: x86_64-w64-mingw32/x64 (64-bit)
## 
## locale:
## [1] LC_COLLATE=English_United Kingdom.1252  LC_CTYPE=English_United Kingdom.1252   
## [3] LC_MONETARY=English_United Kingdom.1252 LC_NUMERIC=C                           
## [5] LC_TIME=English_United Kingdom.1252    
## 
## attached base packages:
## [1] stats     graphics  grDevices utils     datasets  methods   base     
## 
## other attached packages:
##  [1] BiocInstaller_1.12.1 ggplot2_0.9.3.1      reshape2_1.2.2       sos_1.3-8           
##  [5] brew_1.0-6           stringr_0.6.2        knitr_1.5            plyr_1.8            
##  [9] Revobase_7.1.0       RevoMods_7.1.0       RevoScaleR_7.1.0     lattice_0.20-27     
## [13] rpart_4.1-2         
## 
## loaded via a namespace (and not attached):
##  [1] codetools_0.2-8    colorspace_1.2-4   dichromat_2.0-0    digest_0.6.4      
##  [5] evaluate_0.5.1     foreach_1.4.1      formatR_0.10       fortunes_1.5-2    
##  [9] grid_3.0.2         gtable_0.1.2       highr_0.3          iterators_1.0.6   
## [13] labeling_0.2       MASS_7.3-29        munsell_0.4.2      proto_0.3-10      
## [17] RColorBrewer_1.0-5 scales_0.2.3       tools_3.0.2
Sys.time()
## [1] "2014-05-13 15:05:42 BST"