############### ###############
## direct.textable.R
## Project: CBO
## Author: Malte Lierl
## Date of creation: 25/05/2022
############### ###############

# Creating tex tables by directly writing tex code in R

#1.FUNCTIONS TO GENERATE TEX CODE -----
  execute<-function(text) {
    eval(parse(text=text))
  }

  direct.textable<-function(code,file) {
    split.code.1<-unlist(strsplit(code,">>"))
    split.code<-strsplit(split.code.1,"<<")
    if (length(split.code[[1]])<2) {split.code[[1]]<-c('""',split.code[[1]])}
    if (length(split.code[[length(split.code)]])<2) {split.code[[length(split.code)]]<-c(split.code[[length(split.code)]],'""')}
    split.code<-matrix(unlist(split.code),byrow=TRUE,ncol=2)
    split.code[,2]<-sapply(split.code[,2],execute)
    write(t(split.code),file=file,sep="",ncolumns=nrow(split.code)*ncol(split.code))
  }

#2.FUNCTIONS TO GENERATE TEX CODE -----
  stars<-function(x,v,digits) {
    x<-signif(x,digits)
    xcoef<-x[v,1]
    pval<-x[v,4]
    out<-""
    if (pval<=0.1&pval>0.05) {out<-"$^{*}$"}
    if (pval<=0.05&pval>0.01) {out<-"$^{**}$"}
    if (pval<=0.01&pval>0.001) {out<-"$^{***}$"}
    #if (pval<=0.001) {out<-"$^{***}$"}
    return(paste(xcoef,out,sep=""))
  }
