R/weekYCol.R

Defines functions weekYCol

Documented in weekYCol

#' weekYCol
#' @param dfName a string of class character indicating the name of the data.frame object to be used
#' @param dfColName a string of class character indicating the name of the column to be handled. The entries in this column must be dates in the date format given by the parameter \code{dateFormat}
#' @param dateFormat a character string indicating the date format of the column \code{dfColName}
#' @param endRep a character string (default: "end") indicating whether to append the new columns at the end (endRep=="end") or replace the original columns with the respective new columns (endRep=="rep") or insert the new columns right after the respective columns (endRep=="after") in the data.frame object with name \code{dfName}.  
#' @return the modified data.frame object \code{dfName} which now contains a new column containing the week of the year corresponding to the entries in column \code{dfColName} of the original data frame. The entries in the new column are integers in the range [1,53]. If 1 January falls on either of Monday, Tuesday, Wednesday, Thursday then it belongs to week 1, otherwise week 53 of the last year. The first week of the year is the one that contains the first Thursday of the year.
#' @description takes as input a date.frame object (\code{dfName}), a column name (\code{dfColName}), and the date format (\code{dateFormat}) of the column \code{dfColName} and inserts a new column containing the week of the year corresponding to the entries in the column \code{dfColName}. The location of the new column is dictated by \code{endRep}.
#' @examples
#' weekYCol("rice","tillDate","%d.%m.%Y") 
#' weekYCol("rice","tillDate","%d.%m.%Y",F)
#' weekYCol("employees","date_of_birth","%Y-%m-%d")
#' weekYCol("employees","start_date","%Y-%m-%d",F)
#' @export
weekYCol<-function(dfName,dfColName,dateFormat,endRep="end")
{
  dfTab<-get(dfName)
  weekYCol<-data.frame(as.numeric(format(strptime(dfTab[,dfColName],dateFormat),"%V")))
  names(weekYCol)<-paste(dfColName,"W",sep="")

    if (endRep=="end")
    {
      tab<-cbind(tab,weekYCol)
    }
    if (endRep=="rep")
    {
      tab[,dfColName]<-weekYCol
    }
    if (endRep=="after")
    {
      tab<-as.data.frame(append(tab,weekYCol,after=loc.col(tab,dfColName)[[2]]))
    }
   
  assign(dfName,tab,envir=globalenv())
  rm(list=c("tab"))
}
lwTools/agriTrf documentation built on March 26, 2020, 12:09 a.m.