miscellaneous notes:

A simple function has a name, possibly one or more arguments, and a body.

calcGCPct <- function(xSeq) {
  length(which(xSeq %in% c("C","G"))) / length(xSeq)
}
mySeq <- sample(c("A","C","G","T"), 1000, replace = TRUE)

calcGCPct(mySeq)
## [1] 0.519
calcGCPct(mySeq[1:100])
## [1] 0.56

Notes about arguments

makeVector <- function(aa, ab, ba) { c(aa, ab, ba) }
makeVector(1, 2, 3)
## [1] 1 2 3
makeVector(1, 2, aa = 3)
## [1] 3 1 2
makeVector(1, ab = 3,a = 2)
## [1] 2 3 1
makeAlphanumericSample <- function( alphabet, 
                                    seqLength = 1000, 
                                    useProbabilities = NULL) {
  if(is.null(useProbabilities)) 
    useProbabilities <- rep(1/length(alphabet), length(alphabet))
  sample(alphabet, seqLength, replace=TRUE, prob=useProbabilities)
}

makeDNASample <- function(...){
  makeAlphanumericSample(c("A","C","G","T"), ...)
}

makeDNASample(seqLength = 100)
##   [1] "A" "G" "A" "C" "A" "G" "G" "C" "A" "C" "C" "C" "A" "C" "A" "T" "C"
##  [18] "C" "G" "C" "C" "C" "A" "C" "C" "A" "A" "A" "C" "T" "G" "A" "G" "C"
##  [35] "T" "C" "C" "T" "A" "G" "G" "G" "A" "A" "T" "C" "C" "C" "T" "G" "C"
##  [52] "A" "A" "G" "T" "T" "T" "C" "A" "T" "G" "T" "T" "T" "G" "G" "G" "A"
##  [69] "T" "C" "A" "T" "T" "A" "C" "C" "A" "A" "T" "T" "G" "C" "C" "C" "C"
##  [86] "C" "G" "A" "A" "C" "A" "T" "T" "T" "C" "A" "A" "T" "G" "G"
makeDNASample(seqLength = 100, 
              useProbabilities = c(0,.5,.5,0))
##   [1] "G" "C" "G" "G" "C" "C" "C" "G" "G" "C" "C" "C" "C" "G" "C" "C" "C"
##  [18] "C" "G" "C" "G" "C" "C" "G" "C" "G" "C" "G" "C" "C" "G" "C" "C" "C"
##  [35] "G" "C" "G" "G" "G" "G" "G" "G" "G" "C" "C" "C" "C" "C" "C" "C" "G"
##  [52] "C" "G" "G" "C" "C" "C" "C" "C" "C" "C" "G" "G" "C" "G" "G" "C" "G"
##  [69] "C" "C" "G" "C" "G" "C" "G" "C" "C" "C" "G" "C" "C" "C" "C" "G" "C"
##  [86] "C" "C" "C" "C" "C" "G" "C" "G" "G" "C" "G" "G" "C" "G" "G"

Notes about return values:

The following returns NULL:

testFunction <- function(){}
testFunction()
## NULL
testFunction <- function(x) 5+7
testFunction()
## [1] 12
testFunction <- function(x) { 5+7; 13 }
testFunction()
## [1] 13
testFunction <- function(x){
  if(missing(x)) 
    return(0)
  x^2
}
testFunction()
## [1] 0
testFunction(4)
## [1] 16

Notes about scope

testFunction <- function(x){ 
  y <- 5
  x + y 
}
rm(y)
## Warning in rm(y): object 'y' not found
testFunction(2)
## [1] 7
y
## Error: object 'y' not found
y <- 2
testFunction(2)
## [1] 7
y
## [1] 2
testFunction <- function(x) {
  v1 <- x + y
  y <- 10
  v1 + y
}
y<-2
testFunction(4)
## [1] 16
testFunction <- function(x){
  y <<- 5
  x + y
}
rm(y)
testFunction(2)
## [1] 7
y
## [1] 5