R/fun_plot.R

Defines functions fun_plot

Documented in fun_plot

#' Plot Recursive Sequence Function
#'
#' Function that allows a user to input a data frame with four columns, and
#' runs fun_rec_seq to generate a line plot.
#'
#' @importFrom ggplot2 ggplot aes geom_line labs
#'
#' @param df Data frame where the first 3 columns are numeric to be input to
#' function fun_rec_seq and fourth column is positive integer n for sequence to
#' be generated.
#'
#' @return Returns line plot of the output values for different values of n.
#' @export fun_plot
#'
#' @examples
#' my_data <- tibble::tribble(
#' ~x, ~y, ~z, ~n,
#' 2,4,3,3,
#' 2,4,3,4,
#' 2,4,3,5,
#' 2,4,3,6,
#' 2,4,3,7,
#' 2,4,3,8,
#' 2,4,3,9,
#' 2,4,3,10,
#' 2,4,3,12)
#'
#' fun_plot(my_data)

fun_plot <- function(df){
  # Binding for global variables 'n' and 'output' for plot
  n <- output <- NULL

  # Checks if parameter is a data frame and length of 4
  stopifnot(is.data.frame(df),
            length(df) == 4)

  # Create two empty vectors of row length of data frame
  # To combine later into data frame to produce plot
  seq_vec <- vector(mode = "numeric", length = nrow(df))
  n_vec <- vector(mode = "numeric", length = nrow(df))

  # For loop that fills seq_vec with output from function fun_rec_seq
  # and fills n_vec with 'n' from data frame
  for(i in seq_along(seq_vec)){
    seq_vec[i] <- fun_rec_seq(as.numeric(c(df[i,1], df[i,2], df[i,3])),
                              as.integer(df[i,4]))
    n_vec[i] <- df[[i,4]]
  }

  # Combine seq_vec and n_vec into data frame for ggplot
  plot_data <- data.frame(output = seq_vec, n = n_vec)

  # To create title
  plot_seq_title <- "My Sequence: "
  plot_vec_title <- paste0(round(seq_vec, digits = 3), collapse = ", ")

  # ggplot of output and n
  ggplot(plot_data, aes(x = n, y = output)) +
    geom_line() +
    labs(title = paste0(plot_seq_title, plot_vec_title))
}
21Sp-STAT-413-613/hw04p.marc.estevadeordal documentation built on March 1, 2021, midnight