JoeToolFunctions.R 5.28 KB
Newer Older
Jalbert, Joe's avatar
Jalbert, Joe committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#' Standard Error
#'
#' @param data The vector or dataset over which the standard error is calculated
#'
#' @return The calulated Standard Error
#' @importFrom stats sd
#' @export
#'
#' @examples
#' x=c(10, 20, 30, 40, 50)
#' se(x)
se=function(data){
  return(sd(data, na.rm=T)/sqrt(sum(!is.na(data))))
}

#' Flexible Workbook Creation Function
#'
#' @param df The dataframe to be saved
#' @param filename Name of the file, including the xlsx extension
#' @param sheetBy Option to create sheets based on the values in a particular column of the dataframe
#' @param keepNames The function automatically renames the column names with \code{\link[stringr:case]{stringr::str_to_sentence()}}. Setting this to TRUE will leave your column names unaltered
#'
#' @return Creates a Excel workbook from the supplied dataframe
#' @import tidyverse
#' @import xlsx
#' @import lazyeval
#' @export
#'
#' @examples
#' library(datasets)
#' library(tidyverse)
#' library(xlsx)
#' data(iris)
#' wbsave(iris, "Iris report.xlsx")
#' wbsave(iris, "Iris report - by Species.xlsx", sheetBy="Species", keepNames=TRUE)
wbsave=function(df,filename,sheetBy=NULL,keepNames=FALSE){
  if(keepNames==FALSE) {names(df)=str_to_sentence(names(df))}
  if(!is.null(sheetBy)) {sheetBy=str_to_sentence(sheetBy)}
  wb=createWorkbook()
Jalbert, Joe's avatar
Jalbert, Joe committed
40
  df=as.data.frame(df)
Jalbert, Joe's avatar
Jalbert, Joe committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
  TABLE_COLNAMES_STYLE <- CellStyle(wb)+ Font(wb,  heightInPoints=11, color="#44546A", isBold=TRUE)+
    Border(color = "#8EA9DB", position = "BOTTOM", pen="BORDER_THICK")
  sheetAll=createSheet(wb,sheetName = "All")
  wbdata=NULL
  wbAll=NULL
  if(!is.null(sheetBy)) {l=levels(as.factor(df[[sheetBy]]))}
  if(!is.null(sheetBy)) {for (i in l){
    filter_criteria <- interp(~y == x, .values=list(y = as.name(sheetBy), x = i))
    wbdata=df%>%
      filter_(filter_criteria)
    wbAll[[i]]=wbdata
    sheet=createSheet(wb,sheetName = i)
    addDataFrame(wbdata,sheet, colnamesStyle = TABLE_COLNAMES_STYLE)
    autoSizeColumn(sheet, colIndex = 1:ncol(df)+1)
  }}
  addDataFrame(df,sheetAll, colnamesStyle = TABLE_COLNAMES_STYLE)
  autoSizeColumn(sheetAll, colIndex = 1:ncol(df)+1)
  saveWorkbook(wb, filename)
}

#' Creates a Report with t-tests for a Vector of Outcomes
#'
#' @param df Dataframe to use for the report
#' @param Measures A vector of string names for columns to take means for. Order will be used to make the report.
#' @param Factor A binary factor which will be used for comparisons.  Must be 1 (Treatment) or 0 (No_Treatment)
#' @param paired Options for running t-test.  "Yes" forces paired, t-tests, "No" assumes no pairing, and "Try" will try a paired t-test, and follow up with a unpaired t-test if it fails to run.
#'
#' @return
#' @import tidyverse
#' @export
#'
#'
#' @examples

75
report=function(df, Measures, Factor, paired=c("Try","Yes", "No")){
Jalbert, Joe's avatar
Jalbert, Joe committed
76
77
78
79
80
  output=df%>%
    group_by(.data[[Factor]])%>%
    summarise_at(vars(Measures), mean,na.rm=T)%>%
    mutate(Levels =ifelse(.data[[Factor]]==1, "Treatment", "No_Treatment"))%>%
    select(-.data[[Factor]])%>%
Jalbert, Joe's avatar
Jalbert, Joe committed
81
    pivot_longer(cols=Measures, names_to = "Measure")%>%
Jalbert, Joe's avatar
Jalbert, Joe committed
82
83
84
85
86
87
88
    pivot_wider(names_from = "Levels", values_from = "value")%>%
    mutate(Diff=Treatment-No_Treatment)%>%
    mutate(Measure=factor(.data$Measure,levels=Measures))%>%
    arrange(Measure)


  reportpvaluecount=0
Jalbert, Joe's avatar
Jalbert, Joe committed
89
  p=NULL
Jalbert, Joe's avatar
Jalbert, Joe committed
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
  for(i in Measures){
    reportpvaluecount=reportpvaluecount+1
    form=paste0(i, "~",Factor)
    if(paired=="Yes"){p[reportpvaluecount]=as.numeric(try(t.test(formula=as.formula(form), data=df, paired=T)$p.value))}
    else if (paired=="No"){p[reportpvaluecount]=as.numeric(try(t.test(formula=as.formula(form), data=df)$p.value))}
    else {p[reportpvaluecount]=tryCatch(as.numeric(t.test(formula=as.formula(form), data=df, paired=T)$p.value), error=function(err)
      p[reportpvaluecount]=as.numeric(try(t.test(formula=as.formula(form), data=df)$p.value)), finally = NA)}

  }

  output$p_value=p

  output=output%>%
    mutate(Signif=ifelse(p_value<.001, "***",ifelse(p_value<.01, "**",
                                                    ifelse(p_value<.05, "*", ifelse(p_value<.1, ".", "")))))
}
Jalbert, Joe's avatar
Jalbert, Joe committed
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138


#' Appends Interactions to a \code{\link[JoeTools:report]{report()}} Output Dataframe
#'
#' @param report The report dataframe that is being appended
#' @param df The orginal dataframe used for the report
#' @param Measures A vector of string names for the dependant variable. Order must be the same as the repor
#' @param Factor A binary factor (as a string) which will be used for comparisons.  Must be 1 (Treatment) or 0 (No_Treatment)
#' @param Interaction A factor column name (as a string) that will be used as an interacting independant variable.
#'
#' @return
#' @import tidyverse
#' @export
#'
#' @examples
appendInteraction=function(report,df, Measures,Factor,Interaction){
  p=NULL
  reportpvaluecount=0
  for(i in Measures){
    reportpvaluecount=reportpvaluecount+1
    form=paste0(i, "~",Factor,"*",Interaction)
    p[reportpvaluecount]=tryCatch(summary(aov(formula = as.formula(form), data=df))[[1]][["Pr(>F)"]][[3]], error=function(err) NA)
  }
  name=paste0(Interaction,"_pvalue")
  name2=paste0(Interaction,"_Int")
  output=report
  output[[name]]=p
  output=output%>%
    mutate(NewP=ifelse(.data[[name]]<.001, "***",ifelse(.data[[name]]<.01, "**",
                                                        ifelse(.data[[name]]<.05, "*", ifelse(.data[[name]]<.1, ".", "")))))%>%
    rename(!!name2:=NewP)
  
}