Consider the following simple function that produces a DNA sequence:
n = 5 sequence = function() { bases = c("C", "G", "A", "T") n = 10 paste(sample(bases, n, TRUE), collapse = "") } sequence()
## sequence uses the local variable n
sequence()
to allow v
to be passed as an argument, i.e. we can write sequence(5)
. Call this function to make sure it works.sequence = function(n) { bases = c("C", "G", "A", "T") paste(sample(bases, n, TRUE), collapse = "") } sequence(5)
one = function(x = 10) { return(x) } two = function(x) { return(x) }
one()
work, but this raises an error
two()
## two() expects an argument x, but ## we haven't given one and there is ## no default.
sequence
function so that it has a default value for n
.sequence = function(n = 10) { bases = c("C", "G", "A", "T") paste(sample(bases, n, TRUE), collapse = "") } sequence()
So far we have been creating random DNA sequences. Lets do another routine job, split them into codons. You could approach this in a number of ways, but lets start with something like this (you will need the stringr
package).
library(stringr) # create the sequence s = sequence() # establish indeces of the first and last base in the codon offset = 0 start = seq(1 + offset, str_length(s), by = 3) end = start + 2 # retrieve the codons str_sub(s, start, end)
codons
.codons = function(sequence) { offset = 0 start = seq(1 + offset, nchar(sequence), by = 3) end = start + 2 str_sub(sequence, start, end) }
codons = function(sequence, offset = 0) { start = seq(1 + offset, nchar(sequence), by = 3) end = start + 2 str_sub(sequence, start, end) }
codons = function(sequence, offset = 0, length = 3) { start = seq(1 + offset, nchar(sequence), by = length) end = start + length - 1 str_sub(sequence, start, end) }
Solutions are contained within this package:
vignette("solutions2", package = "jrProgBio")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.