#' Modify Specific Elements of a Vector in Different Ways
#'
#' Carry out alternative arithmetic operations on different elements of a vector. Intended for use when specifying plot annotations using objects.
#' @param vector The vector to alter.
#' @param positions The indices of the elements of the vector to alter.
#' @param operations Mathematical operations to carry out (in conjunction with numbers) on the specified vector elements. Some degree of work-around may be needed (i.e. to square a number, set operations to '*' and the numbers element to the same as the vector element).
#' @param numbers The numbers that are used at the end of the operation.
#' @keywords position modify add subtract multiply divide
#' @export
#' @examples
#' vector <- rep(1, times = 5)
#' posmod(vector = vector, positions = c(2, 4), operations = c('+', '-'), numbers = c(1, 1))
#' [1] 1 2 1 0 1
posmod <- function(vector, positions, operations, numbers) {
if ( !identical(length(positions), length(operations), length(numbers)) ) { stop('The number of positions, operations and numbers must be equal.') }
if ( any(positions > length(vector)) || any(positions < 1) ) { stop('Positions outside the vector range cannot be specified.') }
# Maybe an error that checks if all position and number vector elements are actually numbers?
vector[positions] <-
{ lapply(X = 1:length(positions),
FUN = function(pm) {
p <- positions[pm]
o <- operations[pm]
n <- numbers[pm]
eval(parse(text = paste0(vector[p], o, n)))
}) %>%
unlist }
return(vector)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.