R/add_daynight.R

Defines functions add_daynight

Documented in add_daynight

#' Adds day or night to a dataframe.
#'
#' DEPENDENT function: Dependent on add_datetime and is_daynight support functions
#' This function adds a single column of day or night to all rows of a given dataframe. This function builds on and is dependent on the
#'  add_datetime package. How it works is this funciton grabs the time values in the dataframe and determines if it is night or day by
#'  seeing if the hour element is above or below 12. If there is already a day_or_night or time column, the function will print an error message.
#'
#'
#' @param df dataframe
#'
#'
#' @return dataframe
#' @export
#' @examples
#' fruit_harvest <- data.frame(apples = c(4,10,12), oranges = c(8,9,10))
#' add_daynight(df)
#' ##   apples oranges       date     time day_or_night
#' ## 1      4       8 2015-11-26 23:47:15        night
#' ## 2     10       9 2015-11-26 23:47:15        night
#' ## 3     12      10 2015-11-26 23:47:15        night

add_daynight <- function(df) {
  if (any(colnames(df) == "day_or_night")) {

    print("Error: There is already a day_or_night variable in the dataframe")

  } else if (any(colnames(df) == "time")) {

    df2 <- df %>% mutate(day_or_night = is_daynight(time))
    df2
  } else {
    df2 <- add_datetime(df)
    df3 <- df2 %>% mutate(day_or_night = is_daynight(time))
    df3
  }
}
hochoy/r_timekeeper documentation built on May 17, 2019, 4:36 p.m.