#' Replace NAs
#'
#' This function swaps out NA values in an object (vector, matrix - call with lapply for lists) while retaining dimensions and names. If no NA values are found, the object is returned as is.
#' @param possNAs An R object that may or may not contain NA values.
#' @param swap The value to swap NA for. Defaults to 0. Changing to a character value after inputting only numerical values will change ALL numbers to characters if using a matrix.
#' @keywords NA swap change retain dimension
#' @export
#' @examples
#' test.matrix <- matrix(data = c(1, 2, 3, NA, 4, 6), nrow = 2)
#' test.matrix
#' [,1] [,2] [,3]
#' [1,] 1 3 4
#' [2,] 2 NA 6
#'
#' swap_na(test.matrix, swap = 0)
#' [,1] [,2] [,3]
#' [1,] 1 3 4
#' [2,] 2 0 6
swap_na <- function(possNAs, swap = 0) {
if ( any(is.na(possNAs)) == TRUE ) { possNAs[which(is.na(possNAs))] <- swap }
return(possNAs)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.