#' Fill \code{NA} in data.frame with values from another column
#'
#' @description \code{fill_na} fills in any \code{NA} rows in a data.frame
#' column with the corresponding values from another column in
#' the same data.frame. It will coerce the column with \code{NA} into the
#' same type as the column used to fill.
#'
#' This function does not work well with factors.
#'
#' @param df data.frame
#' @param na_col column in \code{df}: contains \code{NA} values
#' @param fill_col column in \code{df}: ccontains values to
#' replace \code{NA} values
#'
#' @return Returns a \code{data.frame} with \code{NA} in a specific
#' column filled with values from another column.
#'
#' @examples
#' # make data.frame with NA
#' my_data <- data.frame(name1 = c("Bob", "Jane", "Henry", "Sue"),
#' name2 = c("Mary", NA, "Tim", NA),
#' stringsAsFactors = FALSE)
#'
#' # fill NA in names2
#' result <- fill_na(df = my_data, na_col = "name2", fill_col = "name1")
#'
#' # make a another data.frame with NA
#' my_data <- data.frame(num1 = c(1, 2, 3),
#' num2 = c(3, 3, NA))
#'
#' # fill NA in num2
#' result <- fill_na(df = my_data, na_col = "num2", fill_col = "num1")
#'
#' @export
fill_na <- function(df, na_col, fill_col) {
df[[na_col]][is.na(df[[na_col]])] <- df[[fill_col]][is.na(df[[na_col]])]
df
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.