#' Fill empty strings ("") in character column of data.frame with values from
#' another column
#'
#' @description \code{fill_blank} fills any empty "" strings in a data.frame
#' character column with the corresponding values from another character,
#' numeric, or boolean column in the same data.frame.
#'
#' @param df data.frame
#' @param blank_col quoted name of character column in \code{df}: contains
#' empty strings
#' @param fill_col quoted name of character, numeric, or boolean column in
#' \code{df}: contains values to replace empty strings
#'
#' @return \code{df} with empty strings in a specific character column filled
#' with strings from another column.
#'
#' @examples
#' # make data.frame with blanks
#' # columns must be data type = character
#' df <- data.frame(name1 = c("Bob", "Jane", "Henry"),
#' name2 = c("Mary", "", ""),
#' num1 = c(1, 2, 3),
#' num2 = c("", "", 7),
#' stringsAsFactors = FALSE)
#'
#' # fill blanks in names2
#' df <- fill_blank(df, "name2", "name1")
#'
#' @export
fill_blank <- function(df, blank_col, fill_col) {
if(!is.data.frame(df)) {
# ensure df is a data.frame
stop("df must be a data.frame!")
} else if(!is.character(df[[blank_col]])) {
# ensure blank column is character vector
stop("Column with blanks to replace must be a character column!")
} else {
# replace blanks with values from fill column
df[[blank_col]] <- as.character(ifelse(df[[blank_col]] == "",
df[[fill_col]],
df[[blank_col]]))
# return the modified data.frame
df
}
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.