#' Mutation
#'
#' @description \code{mutation} is to do mutation for the offspring after breeding.
#' @param parent_1,parent_2 Numeric vectors with binary 0/1 elements. Should be of same length.
#' @param offspring A Numeric vector generated by \code{crossover} and/or other genetic operators.
#' @param m Mutation rate: a numeric value between 0 and 1. By default 0.01.
#' @details Changes an offspring chromosome by randomly introducing one or
#' more alleles in loci where those alleles are not seen in the
#' corresponding loci of either parent chromosome.
mutation <- function(parent_1, parent_2, offspring, m) {
## test whether there are missing arguments
assert_that(!is.null(parent_1) && !is.null(parent_2) && !is.null(offspring) && !(is.null(m)))
# test whether the inputs are numeric vectors
assert_that(is.numeric(parent_1), is.numeric(parent_2), is.numeric(offspring))
## test whether the length of two chromosomes are the same
assert_that(length(parent_1) == length(parent_2))
same <- sum(parent_1 == parent_2)
# two parents have some same genes
if (same != 0) {
same_loci <- which(parent_1 == parent_2)
# alternate the gene 0 to 1 or 1 to 0 with probability m
mutated_offspring = sapply(same_loci, function(x) {
# mutate
if (runif(1) < m) {
return(1-offspring[x])
}
return(offspring[x])
})
offspring[same_loci] <- mutated_offspring
}
## test for the two parents without same genes, offspring unchanged
return(offspring)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.