Primer on Functions in R
The Basics
A function in its simplest form takes some “input” and does “something” and then returns the “result”:
<- function(input){
f # Do "something" to get the result
return(result)
}
So the function “acts” upon the “input” and thereby creates the result. Since we are working with R for Bio Data Science, let us use DNA as an example of input and then choose transcription as the act upon the input, whereby messenger RNA would be the output. This would look like so:
<- function(DNA){
transcribe_dna
# First we initiate
<- ""
mRNA
# Then we elongate by going through all
# of the nucleotides in the input DNA
for( i in 1:nchar(DNA) ){
# To elongate, first we specify
# the i'th nucleotide in the input DNA
<- substr(DNA, i, i)
nucleotide
# Then we define the as of yet unknown
# result of the transcription
<- ""
transcribed_nucleotide
# And then we see if the input nucleotide
# is "a", "c", "g" or "t" and perform the
# appropriate transcription:
if( nucleotide == "a" ){
<- "u"
transcribed_nucleotide else if(nucleotide == "c"){
} <- "g"
transcribed_nucleotide else if(nucleotide == "g"){
} <- "c"
transcribed_nucleotide else if(nucleotide == "t"){
} <- "a"
transcribed_nucleotide
}
# Perform the elongation
<- paste0(mRNA, transcribed_nucleotide)
mRNA
}
# And finally, we terminate
return(mRNA)
}