R/gemini_narrative.R

Defines functions gemini_narrative

Documented in gemini_narrative

#' @title Generate narrative description for an input using Gemini
#' @description Generate a narrative description for a given input (e.g., table, figure) by converting it to a suitable format and sending it to Gemini.
#' @param input Input object. For type = "table", a data.frame should be provided.
#' @param type Type of input. Default is "table". (e.g., "table", "figure")
#' @param ... Additional arguments passed to gemini()
#' @return Narrative description generated by Gemini
#' @export
#' @examples
#' \dontrun{
#' # Example data.frame
#' table_data <- data.frame(
#'   sort = c(1, 1, 2, 2, 2, 3, 3, 3, 4, 4),
#'   category = c(
#'     "Gender", "Gender", "Age Group", "Age Group", "Age Group",
#'     "Race", "Race", "Race", "Ethnicity", "Ethnicity"
#'   ),
#'   type = c(
#'     "F", "M", "<65", ">80", "65-80",
#'     "AMERICAN INDIAN OR ALASKA NATIVE", "BLACK OR AFRICAN AMERICAN", "WHITE",
#'     "HISPANIC OR LATINO", "NOT HISPANIC OR LATINO"
#'   ),
#'   Placebo = c(53, 33, 14, 30, 42, NA, 8, 78, 3, 83),
#'   Xanomeline_High_Dose = c(40, 44, 11, 18, 55, 1, 9, 74, 3, 81),
#'   Xanomeline_Low_Dose = c(50, 34, 8, 29, 47, NA, 6, 78, 6, 78),
#'   stringsAsFactors = FALSE # Do not convert strings to factors
#' )
#' gemini_narrative(table_data)
#' }
#' @importFrom knitr kable
#'
#' @seealso gemini
#'
gemini_narrative <- function(input, type = "table", ...) {
if (type == "table") {
    if (!is.data.frame(input)) {
        stop("Input must be a data.frame when type is 'table'.")
    }
    # Convert data.frame to markdown table string
    markdown_table_string <- knitr::kable(
      input,
      format = "pipe",
      col.names = colnames(input)
    )
    # Create prompt for Gemini
    prompt <- paste0(
      "make narrative description for this ", type, ": \n",
      paste0(markdown_table_string, collapse = '\n')
    )
    # Call gemini function
    result <- gemini(prompt, ...)
    return(result)
  } else {
    stop("Currently only type = 'table' is supported.")
  }
}

Try the gemini.R package in your browser

Any scripts or data that you put into this service are public.

gemini.R documentation built on June 20, 2025, 5:07 p.m.