Question :
data in a folder: How do we help user to read the data ?

Improve : check functions
Example for several functions
NIRS data

Tutorial:Example for several functions
Project paper outline : find a demo paper

package
documentation
single .R file or a function a file ?

Outline

data

1. ERPdata : maybe a formal data for package

2. NIRSdata

preprocessing

1. list_to_df

2. data_select

3. data_summarize

4. downsample

EDA

1.edaplot

2.ciplot

tests

1.chan_test

2.mcplot

ERP only

1. scalpplot

2. topograph


Data

1. ERPdata
2. NIRSdata
library(ERP);require(mnormt);require(fdrtool);library(ggplot2);library(dplyr)
library(erpR);require(akima);library(reshape2);library(boot)
data(ERPsets)
load("ERPdata.RData")

preprocessing

1. list_to_df
2. data_select
3. data_summarize
4. Down sample
list_to_df
It is a function that could transformed a list to a dataframe for our package.
###list2data
list_to_df <- function(list_data,frames){
        # some check function
        for (i in 1:length(list_data)){
                list_data[[i]]$frames <-frames
                list_data[[i]]$list.name <- names(list_data)[i]
        }
        Data_list <- lapply(list_data,melt,id=c("frames","list.name"))
        Data_list <- lapply(Data_list,reshape,
                          timevar = "frames",idvar = c("variable","list.name"),
                          direction = "wide")
        Ana_data <- Data_list[[1]]
        for (i in 2:length(ERPsets)){
                Ana_data <- rbind(Ana_data,Data_list[[i]])
        }
        colnames(Ana_data)[2] <- "Channel"
        rownames(Ana_data) <- 1:dim(Ana_data)[1]
        return(Ana_data)
}
ERP_df <- list_to_df(list_data=ERPsets, # input list_data
                    frames= 1:426) # input frames
ERP_df <- AddExpCondSub(data = ERP_df, # input the transformed data 
                        list.name_col = 1) # list.name column
#ERP_df <- ERP_df[,-1] # remove list name column, Depend on user's need
head(ERP_df[,c(1:3,427:430)],3) # look at the data
        list.name Channel     value.1 value.425 value.426 Experiment
1 Exp1_word_subj1     Fp1  0.36995740 14.160980  9.971283       Exp1
2 Exp1_word_subj1     Fp2 -0.02759907 13.750350  9.678596       Exp1
3 Exp1_word_subj1      F3  0.42971300  6.269233  4.413941       Exp1
  Condition
1      word
2      word
3      word
2. data_select
It could select data by subject and channel
data_select <- function(data,frames,datacol,subjcol=NULL,chancol=NULL,othvarcol=NULL,
                        select_subj=NULL,
                        select_chan=NULL,...){
        # some check function
        subj_select <- function(data,frames,datacol,subjcol,chancol=NULL,othvarcol=NULL,
                       select_subj,...){
                dta <- data
                num <- length(select_subj)
                data_list <- list()
                for (i in 1:num){
                        data_new <- subset(dta,dta[,subjcol]==select_subj[i])
                        data_list[[i]] <- data_new
                }
                data_select <- data_list[[1]]
                if (num != 1) {
                        for (i in 2:num) { 
                                data_select <- rbind(data_select,data_list[[i]])
                        }
                }
                rownames(data_select) <- 1:dim(data_select)[1]
                return (data_select)
        }
        chan_select <- function(data,frames,datacol,subjcol=NULL,chancol,othvarcol=NULL,
                       select_chan,...){
                dta <- data
                num <- length(select_chan)
                data_list <- list()
                for (i in 1:num){
                        data_new <- subset(dta,dta[,chancol]==select_chan[i])
                        data_list[[i]] <- data_new
                }
                data_select <- data_list[[1]]
                if (num != 1){
                        for (i in 2:num){
                                data_select <- rbind(data_select,data_list[[i]])
                        }
                }
                rownames(data_select) <- 1:dim(data_select)[1]
                return (data_select)
        }
        joint_select <- function(data,frames,datacol,subjcol,chancol,othvarcol=NULL,
                        select_subj,
                        select_chan,...){
                dta <- data
                ind_data <- subj_select(dta,frames,datacol,subjcol,chancol,othvarcol,
                               select_subj = select_subj)
                ind_ele_data <- chan_select(ind_data,frames,datacol,subjcol,chancol,othvarcol,
                               select_chan = select_chan)
                rownames(ind_ele_data) <- 1 :dim(ind_ele_data)[1]
                return(ind_ele_data)
        }
        if (is.null(select_subj)==FALSE & is.null(select_chan)==FALSE){
                dta <- joint_select(data = data,frames = frames,
                                    datacol,subjcol,chancol,othvarcol,
                                    select_subj=select_subj,
                                    select_chan=select_chan)
        } else if (is.null(select_subj)==FALSE & is.null(select_chan)== TRUE) { 
                dta <- subj_select(data=data,frames=frames,
                                   datacol,subjcol,chancol,othvarcol,
                                   select_subj=select_subj)
        } else if (is.null(select_chan)==FALSE & is.null(select_subj)== TRUE) {
                dta <- chan_select(data,frames,
                                  datacol,subjcol,chancol,othvarcol,
                                  select_chan=select_chan)
        } else {
                dta <- data
        }
        return(dta)
}
S1S10Fp1Fp2 <- data_select(data = ERPdata,
                          frames = 1:426,
                          datacol = 2:427,
                          subjcol = 430,
                          chancol = 1,
                          othvarcol = c(428:429,431:432),
                          select_subj = c("subj1","subj2"),
                          select_chan=c("CZ","Fp1"))
CZ <- data_select(data = ERPdata,
                          frames = 1:426,
                          datacol = 2:427,
                          subjcol = 430,
                          chancol = 1,
                          othvarcol = c(428:429,431:432),
                          #select_subj = c("subj1","subj10"),
                          select_chan=c("CZ"))
S1S10 <- data_select(data = ERPdata,
                     frames = 1:426,
                     datacol = 2:427,
                     subjcol = 430,
                     chancol = 1,
                     othvarcol = c(428:429,431:432),
                     select_subj = c("subj1","subj10"))
dim(S1S10Fp1Fp2);dim(CZ);dim(S1S10)
## [1]   8 432
## [1]  40 432
## [1] 136 432
3. Data_summarize :
We could aggregate data by the column like conditions, subjects or channel.
data_summarize <- function(data,frames,datacol,subjcol=NULL,chancol=NULL,othvarcol=NULL,
                          summarycol,
                          fun=mean,
                          select_subj=NULL,
                          select_chan=NULL,...){ 
        #some check function
        options(warn=-1) # should close the warnings?
        # selection
        dta <- data_select(data,frames,datacol,subjcol,chancol,othvarcol,
                    select_subj,
                    select_chan)
        # process
        agglength <- length(summarycol)
        aggvar_list <- list(dta[,summarycol[1]])
        if (agglength > 1){
                for (i in 2:agglength ){
                        aggvar_list <- append(aggvar_list,list(dta[,summarycol[i]]))
                }
        }
        aggdata <- aggregate(dta[,datacol],by=aggvar_list,
                             fun,...)
        aggdata <- aggdata[,1:(agglength+length(datacol))]
        for (i in 1: agglength){
                colnames(aggdata)[i] <- colnames(dta)[summarycol[i]]
        }
        rownames(aggdata) <- 1:dim(aggdata)[1] 
        return(aggdata)
}
A <-data_summarize (data = ERPdata,
                    frames = 1:426,
                    datacol = 2:427,
                    #you could put all elements you want to aggregate in datacol argument
                    subjcol = 430,
                    chancol = 1,
                    othvarcol = c(428:429,431:432),
                    summarycol= c(1,429),
                    fun=median,
                    
                    # could also select data
                    select_chan = c("CZ","Fp1"), 
                    select_subj = c("subj1","subj10"))
tail(A[,1:6]);dim(A)
  Channel Condition    value.1    value.2    value.3    value.4
1     Fp1   nonword -1.4049110 -1.9667935 -1.7905150 -1.7634650
2      CZ   nonword -1.8309385 -2.4948925 -2.1159490 -1.9471855
3     Fp1      word  0.4695684  0.1779768 -0.5842498 -0.9740931
4      CZ      word  0.8391661  0.8317206  0.2696740  0.1090901
[1]   4 428
4. Down Sample:
We could down sample the signal
downsample <- function(data,
                       datacol,
                       binwidth=10,
                       movinginterval=NULL) {
        if (is.null(movinginterval) == FALSE) {
             if (movinginterval >= binwidth){stop("movinginterval should not bigger than binwidth!")}
                dta <- data
                dta_signal <- dta[,datacol]
                dta_othvar <- dta[,-datacol]
                num1 <- (dim(dta_signal)[2] - (dim(dta_signal)[2] %% binwidth)) /binwidth
                num2 <- dim(dta_signal)[2] %% binwidth
                dta_downsample <- data.frame(melt(apply(dta_signal[,1:binwidth],1,mean)))
                i = movinginterval - 1
                while ((binwidth+i) <= dim(dta_signal)[2]){
                        dta_downsample <- cbind(dta_downsample,melt(apply(dta_signal[,(1+i):(binwidth+i)],1,mean)))
                        i = i + movinginterval -1
                }
                if (num2 >= 1) {
                        dta_downsample <- cbind(dta_downsample,
                                                value=melt(apply(dta_signal[,(1+i):dim(dta_signal)[2]],1,mean)))
                }
                colnames(dta_downsample) <- paste("value",1:dim(dta_downsample)[2],sep=".")
                dta_final  <- cbind(dta_othvar,dta_downsample)
        } else {
                dta <- data
                dta_signal <- dta[,datacol]
                dta_othvar <- dta[,-datacol]
                num1 <- (dim(dta_signal)[2] - (dim(dta_signal)[2] %% binwidth))/binwidth
                num2 <- dim(dta_signal)[2] %% binwidth
                dta_downsample <- data.frame(melt(apply(dta_signal[,1:binwidth],1,mean)))
                for (i in 1 : num1-1){
                        dta_downsample <- cbind(dta_downsample,
                                        melt(apply(dta_signal[,(i*binwidth+1):((i+1)*binwidth)],
                                                   1,mean)))
                }
                if (num2 == 1) {
                        dta_downsample <- cbind(dta_downsample,
                                         value=dta_signal[,(num1*binwidth+num2)])
                        ###### notice
                }
                if (num2 > 1) {
                        dta_downsample <- cbind(dta_downsample,
                                melt(apply(dta_signal[,(num1*binwidth+1):(num1*binwidth+num2)],
                                           1,mean)))   
                }
                dta_downsample <- dta_downsample[,-1]
                colnames(dta_downsample) <- paste("value",1:dim(dta_downsample)[2],sep=".")
                dta_final  <- cbind(dta_othvar,dta_downsample)
        }
        return(dta_final)
}
down1 <- downsample(data = ERPdata,
                   datacol = 2:427,
                   binwidth = 10,
                   movinginterval=NULL)
down2 <- downsample(data = ERPdata,
                   datacol = 2:427,
                   binwidth = 10,
                   movinginterval=9) # movinginterval shoud not bigger than binwidth
dim(down1)  ;  dim(down2)
[1] 1360   49
[1] 1360   60

EDA

1.edaplot
2.bootplot
1.edaplot
The function “edaplot”" uses ggplot2 grammar, so it has several flexible options.
# group comparison please put in data after aggregate_raw
edaplot <- function(data,frames=NULL,datacol,subjcol=NULL,chancol=NULL,othvarcol=NULL,
                             outlinesub=NULL,outcolor="red",
                             select_subj=c(NULL),
                             select_chan=c(NULL),...){
        #some check functions
        #if (is.null(frames) == FALSE) 
        #        if (length(frames) != (ncol(data)-1-length(othvarcol)))
        #                stop(paste("frames should be either null or of length",
        #                           (ncol(data)-1-length(othvarcol))))
        #if (is.null(frames) == FALSE) {
        #        if (any(frames != sort(frames))) 
        #                stop("frames should be an ascending sequence of integers")
        #        }
        #if (is.null(frames)) 
        #        frames = 1:(ncol(data)-1-length(othvarcol))
        #selection
        dta <- data_select(data,frames,datacol,subjcol,chancol,othvarcol,
                        select_subj,
                        select_chan,...)
        # plot
        subvar <- variable.names(dta)[subjcol]
        dta$groupvar <- rownames(dta)
        datalong <- melt(dta,
                         id=c(variable.names(dta)[c(subjcol,chancol,othvarcol)],
                              "groupvar"))
        datalong <- datalong[order(datalong$groupvar),]
        datalongorder <- datalong
        datalongorder$frames <- rep(frames,length(datalongorder[,1])/length(frames))
        if (is.null(outlinesub) == FALSE){  # how to outline several subjects (and color)
                data2 <- subset(datalongorder,datalongorder[,1]==outlinesub)
                plot <- ggplot(datalongorder,
                               aes(x=frames,y=value,group=groupvar,...))+
                        geom_line()+
                        geom_line(data=data2,aes(x=frames,y=value),col=outcolor)
        # need warning for covering geom_line()
        } else {
                plot <- ggplot(datalongorder,
                               aes(x=frames,y=value,group=groupvar))+
                        geom_line()
        }
        return(plot)
}
#Although Full data (all trials) work fine, I recommened that the argument erpdata should be a single subject data or an aggregate data.
edaplot(ERPdata,
        frames = 1:426,
        datacol=2:427,
        subjcol=430,
        chancol=1,
        othvarcol=c(428:429,431:432),
        
        # choose the subject you want to show(optional)
        select_sub = c("subj9","subj1","subj5","subj8"), 
        # choose the channel you want to show(optional)
        select_chan = c("F3","F4"))+
        
        facet_grid(Channel~Condition)

edaplot(ERPdata,
        frames = 1:426,
        datacol=2:427,
        subjcol=430,
        chancol=1,
        othvarcol=c(428:429,431:432),
        
        # choose the subject you want to show(optional)
        select_sub = c("subj9","subj1","subj5","subj8"), 
        # choose the channel you want to show(optional)
        select_chan = c("F3","F4"),
        
        # highlight a single subject with the color you want
        outlinesub="subj9",outcolor = "blue")+
        
        facet_grid(Channel~Condition)

edaplot(ERPdata,
        frames=1:426,
        datacol = 2:427,subjcol=430,chancol=1,othvarcol=c(428:429,431:432),
        select_chan = c("F3","F4","CZ"),
        select_sub = c("subj9","subj1","subj5","subj8"))+
        
        # One subject one color
        geom_line(aes(col=Subject))+  # will cover outline sub
        
        facet_grid(Condition~Channel)

edaplot(ERPdata,
        frames=1:426,
        datacol = 2:427,subjcol=430,chancol=1,othvarcol=c(428:429,431:432),
        select_chan = c("F3","F4","CZ"))+
        
        #  Color depend on IQ (Size , alpha either)
        geom_line(aes(col=IQ,alpha=Channel,size=Condition))+ 
        facet_grid(Condition~Channel)

edaplot(ERPdata,
        frames=1:426,
        datacol = 2:427,subjcol=430,chancol=1,othvarcol=c(428:429,431:432),
        select_chan = c("F3","F4","CZ"))+
        # One Condition one color
        geom_line(aes(col=Condition))+
        facet_grid(.~Channel)

edaplot(ERPdata,
        frames=1:426,
        datacol = 2:427,subjcol=430,chancol=1,othvarcol=c(428:429,431:432),
        select_chan = c("F3","F4","CZ"))+
        # One Condition one color
        geom_line(aes(col=Condition))+
        facet_grid(.~Channel)+
        scale_colour_manual(values=c("red","blue"),name="Cond",label=c("A","B"))

edaplot(ERPdata,
        frames=1:426,
        datacol = 2:427,subjcol=430,chancol=1,othvarcol=c(428:429,431:432),
        select_chan = c("F3","F4","CZ"))+
        geom_line(aes(col=Condition))+
        facet_grid(Condition~Channel)

edaplot(ERPdata,
        frames=1:426,
        datacol = 2:427,subjcol=430,chancol=1,othvarcol=c(428:429,431:432),
        select_chan = c("F3","F4","CZ"))+
        geom_line(aes(col=Condition))+
        facet_grid(Condition~Channel)+
        # put on the summary line NOTE: need a group=NULL argument 
        stat_summary(aes(group=NULL),fun.y = "mean", 
                     colour = "purple", size = 0.5, geom = "line")

edaplot(ERPdata,
        frames=1:426,
        datacol = 2:427,subjcol=430,chancol=1,othvarcol=c(428:429,431:432),
        select_chan = c("F3","F4","CZ"))+
        geom_line(aes(col=Condition))+
        facet_grid(Condition~Channel)+
        theme_bw()+
        theme(legend.position="top")+
        xlim(-100,500)+
        ylim(-50,50)+
        labs(list(title = "Flexible",x="time",y="signal"))+
        geom_vline(xintercept = c(0,213,426),col="yellow")

2.ciplot
ciplot use a bootstaping method to draw the confidence interval on two (or more) compared
variable.
ciplot <- function(data,frames,datacol,subjcol=NULL,chancol=NULL,othvarcol=NULL,
                   cpvarcol=NULL, signal_line_col="black",
                   fun=samplemean <- function(x, d){return(mean(x[d]))},  # very unfriendly setting
                   bootnum=500,
                   bootintval=c(.025,.975),
                   bootalpha=0.3,
                   select_subj = NULL,
                   select_chan = NULL,...){
        # need some check function
        bootstrap <- function(x,bootnum,bootfun,bootintval=c(0.025,0.975),quantilenum,...){
                boot_result <- boot(x,statistic = bootfun,R = bootnum,...) #fun
                return(quantile(boot_result$t,bootintval,na.rm = T)[quantilenum])
        }
        # data selection
        dta <- data_select(data,frames,datacol,subjcol,chancol,othvarcol,
                        select_subj,
                        select_chan,...)
        # Do you want to compare between variable ?
        if (is.null(cpvarcol)==TRUE){
            data_fun <- data_summarize(dta,frames,datacol,subjcol,chancol,othvarcol,
                                       summarycol = c(chancol),fun=fun)
            data_Q1 <- data_summarize(dta,frames,datacol,subjcol,chancol,othvarcol,
                                      summarycol = c(chancol),
                                      fun=bootstrap,bootnum=bootnum,bootfun=fun,
                                      bootintval=bootintval,quantilenum=1)
            data_Q2 <- data_summarize(dta,frames,datacol,subjcol,chancol,othvarcol,
                                      summarycol = c(chancol),
                                      fun=bootstrap,bootnum=bootnum,bootfun=fun,
                                      bootintval=bootintval,quantilenum=2)
            data_fun_long <- melt(data_fun,id=c(colnames(dta)[chancol]))
            data_fun_long <- data_fun_long[order(data_fun_long[,1],
                                                 data_fun_long[,2],
                                                 data_fun_long[,3]),]
            colnames(data_fun_long)[3] <- "FUN"
            data_Q1_long <- melt(data_Q1,id=c(colnames(dta)[chancol]))
            data_Q1_long <- data_Q1_long[order(data_Q1_long[,1],
                                               data_Q1_long[,2],
                                               data_Q1_long[,3]),]
            data_Q2_long <- melt(data_Q2,id=c(colnames(dta)[chancol]))
            data_Q2_long <- data_Q2_long[order(data_Q2_long[,1],
                                               data_Q2_long[,2],
                                               data_Q2_long[,3]),]
            data_fun_long$Q1 <- data_Q1_long[,3]
            data_fun_long$Q2 <- data_Q2_long[,3]
            data_fun_long$frames <- c(rep(frames,(dim(data_fun_long)[1]/length(frames)))) #change
            colnames(data_fun_long)[1] <- c("Channel")
            plot <- ggplot(data_fun_long,aes(x=frames))+
                    geom_ribbon(aes(x=frames, ymax=Q2, ymin=Q1),
                                fill=signal_line_col,
                                alpha=bootalpha)+
                    geom_line(aes(y = FUN),
                              col=signal_line_col)+ 
                    labs(y="Signal")+# Need some changes ?
                    facet_wrap(~Channel)+
                    theme(legend.position="none")
        } else {
                dta[,cpvarcol] <- as.factor(dta[,cpvarcol])
                dta[,chancol] <- as.factor(dta[,chancol])
                data_fun <- data_summarize(dta,frames,datacol,subjcol,chancol,othvarcol,
                                           summarycol = c(chancol,cpvarcol),fun=fun)
                data_Q1 <- data_summarize(dta,frames,datacol,subjcol,chancol,othvarcol,
                                          summarycol = c(chancol,cpvarcol),
                                          fun=bootstrap,bootnum=bootnum,bootfun=fun,
                                          bootintval=bootintval,quantilenum=1)
                data_Q2 <- data_summarize(dta,frames,datacol,subjcol,chancol,othvarcol,
                                          summarycol = c(chancol,cpvarcol),
                                          fun=bootstrap,bootnum=bootnum,bootfun=fun,
                                          bootintval=bootintval,quantilenum=2)
                data_fun_long <- melt(data_fun,id=c(colnames(dta)[chancol],colnames(dta)[cpvarcol]))
                data_fun_long <- data_fun_long[order(data_fun_long[,1],
                                             data_fun_long[,2],
                                             data_fun_long[,3]),]
                colnames(data_fun_long)[4] <- "FUN"
                data_Q1_long <- melt(data_Q1,id=c(colnames(dta)[chancol],colnames(dta)[cpvarcol]))
                data_Q1_long <- data_Q1_long[order(data_Q1_long[,1],
                                                   data_Q1_long[,2],
                                                   data_Q1_long[,3]),]
                data_Q2_long <- melt(data_Q2,id=c(colnames(dta)[chancol],colnames(dta)[cpvarcol]))
                data_Q2_long <- data_Q2_long[order(data_Q2_long[,1],
                                                   data_Q2_long[,2],
                                                   data_Q2_long[,3]),]
                data_fun_long$Q1 <- data_Q1_long[,4]
                data_fun_long$Q2 <- data_Q2_long[,4]
                data_fun_long$frames <- c(rep(frames,(dim(data_fun_long)[1]/length(frames))))
                colnames(data_fun_long)[1:2] <- c("Channel","Condition")
                plot <- ggplot(data_fun_long,aes(x=frames,group=Condition))+
                        geom_ribbon(aes(x=frames, ymax=Q2, ymin=Q1,fill=Condition),
                                    alpha=bootalpha)+
                        geom_line(aes(y = FUN,col=Condition))+ 
                        labs(y="Signal")+# Need some changes ?
                        facet_wrap(~Channel)
            }
        return(plot)
}

ciplot(ERPdata, # input the data
       frames=1:426, 
       datacol=2:427,
       subjcol=430,
       chancol=1,
       othvarcol=c(428:429,431:432),
       
       # Important : the column of that single variable you want to compare
       # and if (NULL) the function will return a single line and interval 
       cpvarcol = NULL , 
       signal_line_col = "blue", # work if cpvarcol = NULL
       
       # boot package 
       fun=samplemean <- function(x, d){return(mean(x[d]))}, # the function use to draw boot interval and line
       bootnum=300, # bootsraping number 
       bootintval=c(.025,.975), # bootstrap confidence interval 
       bootalpha=0.5,# the value of alpha on the plot
       #sim = "parametric", #  other setting in "boot package"
       
       # Data selection
       select_chan = c("Fp1","Fp2"))+  # select data
       #select_subj = c("subj1","subj2","subj3","subj10"))+
        
        #other setting in ggplot2
        ylim(-5,5)

ciplot(ERPdata, # input the data
       frames=1:426, 
       datacol=2:427,
       subjcol=430,
       chancol=1,
       othvarcol=c(428:429,431:432),

       # have cpvarcol 
       cpvarcol = 429 , 
       #signal_line_col = "blue",
       
       
       fun=samplemean <- function(x, d){return(mean(x[d]))},
       bootnum=300,
       bootintval=c(.025,.975),
       bootalpha=0.5)+
        ylim(-10,10)+
        #other setting in ggplot2
        scale_fill_manual(values=c("red","blue"),name="Word or Non Word",label=c("No","Yes"))+
        scale_colour_manual(values=c("red","blue"),name="Word or Non Word",label=c("No","Yes"))+
        theme(legend.position = "bottom")

tests

1.chan_test
2.mcplot
1.multichtest
chan_test <- function(data,datacol,chancol,
                      testtype="erpfatest",
                      # do not specify model.matrix like original test function###
                      design_model,
                      # do not specify model.matrix like original test function
                      design0_model=NULL,...){
        
        dta <- data
        dta[,chancol]=as.factor(dta[,chancol])
        levelnum <- length(levels(dta[,chancol]))
        if (levelnum == 1) {
                design <- model.matrix(design_model,data=data)
                if (is.null(design0_model)==F){
                        design0 <- model.matrix(design0_model,data=data)
                }
                if ( testtype == "erpavetest" ){
                       test_list <- erpavetest(dta[,datacol],design,design0,...)
                }
                if (testtype == "erpfatest") {
                        test_list <- erpfatest(dta[,datacol],design,design0,...)
                }
                if (testtype == "erptest") {
                        test_list <- erptest(dta[,datacol], design, design0,...)
                }
                if (testtype == "gbtest") {
                        test_list <- gbtest(dta[,datacol], design, design0,...)
                }
        } else {
                test_list=list()
                dta_list=list()
                for (i in 1:levelnum) {
                        dta_list[[i]] <- subset(dta,dta[,chancol]==(levels(dta[,chancol])[i]))
                        design <- model.matrix(design_model,data=dta_list[[i]])
                        if (is.null(design0_model)==F){
                                design0 <- model.matrix(design0_model,data=dta_list[[i]])
                        }
                        if ( testtype == "erpavetest" ){
                                test_list[[i]] <- erpavetest(dta_list[[i]][,datacol],
                                                             design,design0,...)
                        }
                        if (testtype == "erpfatest") {
                                test_list[[i]] <- erpfatest(dta_list[[i]][,datacol],
                                                            design,design0,...)
                        }
                        if (testtype == "erptest") {
                                test_list[[i]] <- erptest(dta_list[[i]][,datacol],
                                                          design, design0,...)
                        }
                        if (testtype == "gbtest") {
                                test_list[[i]] <- gbtest(dta_list[[i]][,datacol],
                                                         design, design0,...)
                        }
                        names(test_list)[i] <- levels(dta[,chancol])[i]
                }
        }
        return(test_list)
}
ERP_test <- chan_test(ERPdata,2:427,chancol=1,testtype="erpfatest",         
            design_model=(~Subject+Condition), # do not specify "model.matrix" like original test function
            design0_model=(~Subject)) # do not specify "model.matrix" like original test function
        # other seeting in ERP package
2. mcplot
plot original signal curve and highlight the significant location
and it is possible to add some bootstrap interval
mcplot <- function(tests_rst,
                   type = "test", # type = "test" or "signal"
                   multi = F, # IMPORTANT : depend on your tests rst 
                   # IMPORTANT : Work only if type = test
                   cor = FALSE, 
                   # IMPORTANT : depend on your tests rst and data
                   data,frames,datacol,subjcol=NULL,chancol=NULL,othvarcol=NULL,cpvarcol=NULL,
                   significant_col = "pink" , significant_alpha = 0.2,
                   # IMPORTANT : work only if type = signal
                   wantbootplot = FALSE, 
                   fun = samplemean <- function(x, d){return(mean(x[d]))},
                   bootnum = 10,
                   bootintval = c(.025,.975),
                   bootalpha = 0.3 ) {
        
        options(warn=-1) 
        # some check functions
        
        if (type == "test") {
                if (multi==FALSE){
                        data <- data.frame(signal=as.numeric(tests_rst$signal))
                        data$frames = frames
                        data$significant <- 
                                ifelse(data$frames %in% data$frames[tests_rst$significant],
                                   "sig","non-sig")
                        data$sign_frames <- 
                                ifelse(data$frames %in% data$frames[tests_rst$significant],
                                       data$frames,NA)
                        data$group <- rep(0,length(data$signal))
                        data$r2 <- tests_rst$r2
                        if (cor == TRUE){
                                plot <- ggplot(data,
                                               aes(x=frames,y=sign(signal)*sqrt(r2),group=group))+
                                        geom_vline(data=data,
                                                   aes(xintercept = sign_frames,
                                                       col=significant_col),
                                                   alpha=significant_alpha)+
                                        geom_line()+
                                        labs(y = "Correlation")+
                                        theme(legend.position="none")
                        } else {
                                plot <- ggplot(data,aes(x=frames,y=signal,group=group))+
                                        geom_vline(data=data,
                                                   aes(xintercept = sign_frames),
                                                       col=significant_col,
                                                   alpha=significant_alpha)+
                                        geom_line()+
                                        labs(y = "Signal")+
                                        theme(legend.position="none")
                        }
                } else {
                        listlen <- length(tests_rst)
                        data_list <- list()
                        for (k in 1:listlen){
                        data_list[[k]] <- data.frame(signal=as.numeric(tests_rst[[k]]$signal))
                        data_list[[k]]$frames = frames
                        data_list[[k]]$significant<-ifelse(data_list[[k]]$frames %in% data_list[[k]]$frames[tests_rst[[k]]$significant],"sig","non-sig")
                        data_list[[k]]$sign_frames <- ifelse(data_list[[k]]$frames %in% data_list[[k]]$frames[tests_rst[[k]]$significant],data_list[[k]]$frames,NA)
                        data_list[[k]]$group <- rep(0,length(data_list[[k]]$signal))
                        data_list[[k]]$r2 <- tests_rst[[k]]$r2
                        data_list[[k]]$Channel <- names(tests_rst)[k]
                        }
                        data_plot <- data_list[[1]]
                        for (j in 2 : listlen){
                                data_plot <- rbind(data_plot,data_list[[j]])
                        }
                        if (cor == TRUE){
                        plot <- ggplot(data_plot,aes(x=frames,y=sign(signal)*sqrt(r2),group=group))+
                                geom_vline(data=data_plot,
                                                   aes(xintercept = sign_frames),
                                                       col=significant_col,
                                                   alpha=significant_alpha)+
                                geom_line()+
                                facet_wrap(~Channel)+
                                labs(y = "Correlation")+
                                theme(legend.position="none")
                        } else {
                                plot <- ggplot(data_plot,aes(x=frames,y=signal,group=group))+
                                        geom_vline(data=data_plot,
                                                   aes(xintercept = sign_frames),
                                                       col=significant_col,
                                                   alpha=significant_alpha)+
                                        geom_line()+
                                        labs(y="Signal")+
                                        facet_wrap(~Channel)+
                                        theme(legend.position="none")
                        }
                }
        } 
        if (type == "signal") {
                bootstrap <- function(x,bootnum,bootfun,bootintval=c(0.025,0.975),quantilenum,...){
                boot_result <- boot(x,statistic = bootfun,R = bootnum,...) #fun
                return(quantile(boot_result$t,bootintval,na.rm = T)[quantilenum])}
                dta <- data  # selection ?
                if (multi == F ){
                        data_sign <- data.frame(frames=frames)
                        data_sign$significant <- 
                                ifelse(data_sign$frames %in% data_sign$frames[tests_rst$significant],"sig","non-sig")
                        data_sign$sign_frames <- 
                                ifelse(data_sign$frames %in% data_sign$frames[tests_rst$significant],data_sign$frames,NA)
                        data_sign$group <- rep(0,length(frames))
                        plot <- ciplot(dta,frames,
                                       datacol,subjcol,chancol,othvarcol=othvarcol,
                                       cpvarcol,
                                       fun = fun,bootnum,bootintval=bootintval,
                                       bootalpha=ifelse(wantbootplot==T,bootalpha,0))+          
                                geom_vline(data=data_sign,
                                           aes(xintercept = sign_frames),
                                               col=significant_col,
                                           alpha=significant_alpha)+
                                labs(y="Signal")
                }
                if (multi == T) { 
                        listlen <- length(tests_rst)
                        test_list = list()
                        for (i in 1: listlen){
                                test_list[[i]] <- data.frame(frames=frames)
                                test_list[[i]]$significant <- 
                                        ifelse(test_list[[i]]$frames %in% test_list[[i]]$frames[tests_rst[[i]]$significant],"sig","non-sig")
                                test_list[[i]]$sign_frames <- 
                                        ifelse(test_list[[i]]$frames %in% test_list[[i]]$frames[tests_rst[[i]]$significant],test_list[[i]]$frames,NA)
                                test_list[[i]]$group <- rep(0,length(frames))
                                test_list[[i]]$Channel <- names(tests_rst)[i]
                        }
                        test_plot <- test_list[[1]]
                        for (k in 2:listlen){
                                test_plot <- rbind(test_plot,test_list[[k]])
                        }
                        if (is.null(cpvarcol)==TRUE){
                                data_fun <- data_summarize(dta,frames,
                                                           datacol,subjcol,chancol,othvarcol,
                                                           summarycol = c(chancol),fun=fun)
                                data_Q1 <- data_summarize(dta,frames,
                                                          datacol,subjcol,chancol,othvarcol,
                                                          summarycol = c(chancol),
                                                          fun=bootstrap,
                                                          bootnum=bootnum,bootfun=fun,
                                                          bootintval=bootintval,quantilenum=1)
                                data_Q2 <- data_summarize(dta,frames,
                                                          datacol,subjcol,chancol,othvarcol,
                                                          summarycol = c(chancol),
                                                          fun=bootstrap,bootnum=bootnum,bootfun=fun,
                                                          bootintval=bootintval,quantilenum=2)
                                data_fun_long <- melt(data_fun,id=c(colnames(dta)[chancol]))
                                data_fun_long <- data_fun_long[order(data_fun_long[,1],
                                                                     data_fun_long[,2],
                                                                     data_fun_long[,3]),]
                                colnames(data_fun_long)[3] <- "FUN"
                                data_Q1_long <- melt(data_Q1,id=c(colnames(dta)[chancol]))
                                data_Q1_long <- data_Q1_long[order(data_Q1_long[,1],
                                                                   data_Q1_long[,2],
                                                                   data_Q1_long[,3]),]
                                data_Q2_long <- melt(data_Q2,id=c(colnames(dta)[chancol]))
                                data_Q2_long <- data_Q2_long[order(data_Q2_long[,1],
                                                                   data_Q2_long[,2],
                                                                   data_Q2_long[,3]),]
                                data_fun_long$Q1 <- data_Q1_long[,3]
                                data_fun_long$Q2 <- data_Q2_long[,3]
                                data_fun_long$frames <- c(rep(frames,
                                                            (dim(data_fun_long)[1]/length(frames))))
                                colnames(data_fun_long)[1] <- c("Channel")
                                data_plot <- merge(data_fun_long,
                                                   test_plot,
                                                   by =c("Channel","frames"))
                                plot <- ggplot(data_plot,aes(x=frames))+
                                        geom_vline(aes(xintercept = sign_frames),
                                                       col=significant_col,
                                                   alpha=significant_alpha)+
                                        geom_ribbon(aes(x=frames, ymax=Q2, ymin=Q1),
                                                    alpha=ifelse(wantbootplot==T,bootalpha,0))+
                                        geom_line(aes(y = FUN))+
                                        facet_wrap(~Channel)+
                                        labs(y="Signal")+
                                        theme(legend.position="none")
                        } else {
                                dta[,cpvarcol] <- as.factor(dta[,cpvarcol])
                                dta[,chancol] <- as.factor(dta[,chancol])
                                data_fun <- data_summarize(dta,frames,
                                                           datacol,subjcol,chancol,othvarcol,
                                                           summarycol = c(chancol,cpvarcol),fun=fun)
                                data_Q1 <- data_summarize(dta,frames,
                                                          datacol,subjcol,chancol,othvarcol,
                                                          summarycol = c(chancol,cpvarcol),
                                                          fun=bootstrap,bootnum=bootnum,bootfun=fun,
                                                          bootintval=bootintval,quantilenum=1)
                                data_Q2 <- data_summarize(dta,frames,
                                                          datacol,subjcol,chancol,othvarcol,
                                                          summarycol = c(chancol,cpvarcol),
                                                          fun=bootstrap,bootnum=bootnum,bootfun=fun,
                                                          bootintval=bootintval,quantilenum=2)
                                data_fun_long <- melt(data_fun,
                                                      id=c(colnames(dta)[chancol],
                                                           colnames(dta)[cpvarcol]))
                                data_fun_long <- data_fun_long[order(data_fun_long[,1],
                                                                     data_fun_long[,2],
                                                                     data_fun_long[,3]),]
                                colnames(data_fun_long)[4] <- "FUN"
                                data_Q1_long <- melt(data_Q1,
                                                     id=c(colnames(dta)[chancol],
                                                          colnames(dta)[cpvarcol]))
                                data_Q1_long <- data_Q1_long[order(data_Q1_long[,1],
                                                                   data_Q1_long[,2],
                                                                   data_Q1_long[,3]),]
                                data_Q2_long <- melt(data_Q2,
                                                     id=c(colnames(dta)[chancol],
                                                          colnames(dta)[cpvarcol]))
                                data_Q2_long <- data_Q2_long[order(data_Q2_long[,1],
                                                                   data_Q2_long[,2],
                                                                   data_Q2_long[,3]),]
                                data_fun_long$Q1 <- data_Q1_long[,4]
                                data_fun_long$Q2 <- data_Q2_long[,4]
                                data_fun_long$frames <- 
                                        c(rep(frames,(dim(data_fun_long)[1]/length(frames))))
                                colnames(data_fun_long)[1:2] <- c("Channel","Condition")
                                data_plot <- merge(data_fun_long,
                                                   test_plot,
                                                   by =c("Channel","frames"))
                                plot <- ggplot(data_plot,aes(x=frames,group=Condition))+
                                        geom_vline(aes(xintercept = sign_frames),
                                                       col=significant_col,
                                                   alpha=significant_alpha)+
                                        geom_ribbon(aes(x=frames, ymax=Q2, ymin=Q1,fill=Condition),
                                                    alpha=bootalpha)+
                                        geom_line(aes(y = FUN,col=Condition))+ 
                                        labs(y="Signal")+# Need some changes ?
                                        facet_wrap(~Channel)+
                                        theme(legend.position="none")
                                        
                        }
                }
        }
        return(plot)
}
#### type = test ; multi = TRUE ; cor = FALSE


ERP_test <- chan_test(ERPdata,2:427,chancol=1,testtype="erpfatest",         
            design_model=(~Subject+Condition),
            design0_model=(~Subject))


mcplot(tests_rst = ERP_test,
       # You could select , type = "test" or "signal"
       type = "test",
       
       # it is depend on your tests rst 
       multi = T, 
       
       # Work only if type = test
       cor = FALSE,
       
       # data information
       data = ERPdata , frames = 1:426 , datacol = 2:427, subjcol = 430 , chancol = 1 , othvarcol = c(428:429,431:432),
       
       # it is depend on your tests rst 
       # if type is "test" , it is not important
       # cpvarcol = 429 ,
       
       # the color of significant window
       significant_col = "pink" , significant_alpha = 0.2)

       # only if type = signal
       # wantbootplot = TRUE, 
       # fun = samplemean <- function(x, d){return(mean(x[d]))}, # boot package
       # bootnum = 10,
       # bootintval = c(.025,.975),
       # bootalpha = 0.3 )



#### type = test ; multi = FALSE ; cor = FALSE

# select CZ data
CZ <- data_select(data = ERPdata,frames = 1:426,
                  datacol = 2:427,subjcol = 430,chancol = 1,othvarcol = c(428:429,431:432),
                  select_chan=c("CZ"))
CZ_test <- erpfatest(CZ[2:427],
          design=model.matrix(~Subject+Condition,data=CZ),
          design0=model.matrix(~Subject,data=CZ))

mcplot(tests_rst = CZ_test,
       type = "test",
       
       # Single Channel, So multi = FALSE
       multi = F,
       
       
       cor = FALSE,
       data = CZ , frames = 1:426 ,
       datacol = 2:427, subjcol = 430 , chancol = 1 , 
       othvarcol = c(428:429,431:432) , cpvarcol = 429 ,
       significant_col = "lightblue" , significant_alpha = 0.5)

#### type = test; multi = T ; cor = T
ERP_cor_test <- chan_test(ERPdata,2:427,chancol=1,testtype="erpfatest",         
            design_model=(~IQ+Condition),
            design0_model=(~Condition))
mcplot(tests_rst = ERP_cor_test ,
       type = "test",
       multi = T,
       
       # Work only if type = test
       cor = T,
       data = ERPdata , frames = 1:426 ,
       datacol = 2:427, subjcol = 430 , chancol = 1 , 
       othvarcol = c(428:429,431:432) , cpvarcol = 429 ,
       significant_col = "lightblue" , significant_alpha = 0.5)

# type = test; multi = F ; cor = T
CZ <- data_select(data = ERPdata,frames = 1:426,
                  datacol = 2:427,subjcol = 430,chancol = 1,othvarcol = c(428:429,431:432),
                  select_chan=c("CZ"))
CZ_word <- subset(CZ,CZ$Condition=="word")
CZ_word_test <- erpfatest(CZ_word[2:427],
          design=model.matrix(~IQ,data=CZ_word))
mcplot(tests_rst = CZ_word_test ,
       type = "test",
       multi = F,
       
       # Work only if type = test
       cor=T,
       
       data=CZ_word,frames=1:426,datacol=2:427,subjcol=430,chancol=1,othvarcol=c(428:429,431:432), #cpvarcol = NULL ,
       significant_col = "purple" , significant_alpha = 0.2)

# type = signal ; multi = FALSE ; Have cpvar 
CZ <- data_select(data = ERPdata,frames = 1:426,
                  datacol = 2:427,subjcol = 430,chancol = 1,othvarcol = c(428:429,431:432),
                  select_chan=c("CZ"))
CZ_test <- erpfatest(CZ[2:427],
          design=model.matrix(~Subject+Condition,data=CZ),
          design0=model.matrix(~Subject,data=CZ))
mcplot(tests_rst = CZ_test ,
       
       # type = "test" or "signal"
       type = "signal", 
       
       
       # depend on your tests_rst
       multi = F,
       
       # only if type = test
       cor = FALSE,
       
       data = CZ  , frames = 1:426 ,datacol = 2:427, subjcol = 430 , chancol = 1 , othvarcol = c(428:429,431:432) ,
       
       # depend on your r=test rst setting
       cpvarcol = 429 ,
       
       # the color of significant window
       significant_col = "pink" , significant_alpha = 0.2,
       
       # boot strap
       wantbootplot = TRUE, 
       fun = samplemean <- function(x, d){return(mean(x[d]))},
       bootnum = 10,
       bootintval = c(.025,.975),
       bootalpha=0.3)+
        ylim(-10,10)

# type = signal ; multi = FALSE ; No cpvar (similar to correlation or simple T test setting)
CZ <- data_select(data = ERPdata,frames = 1:426,
                  datacol = 2:427,subjcol = 430,chancol = 1,othvarcol = c(428:429,431:432),
                  select_chan=c("CZ"))
CZ_word <- subset(CZ,CZ$Condition=="word")
CZ_word_test <- erpfatest(CZ_word[2:427],
          design=model.matrix(~IQ,data=CZ_word))

mcplot(tests_rst = CZ_word_test ,
       type = "signal", # type = "test" or "signal"
       multi = F,
       cor = FALSE, # only if type = test
       data = CZ_word  , frames = 1:426 ,datacol = 2:427, subjcol = 430 , chancol = 1 , othvarcol = c(428:429,431:432) , 
       # No cpvar (similar to correlation or simple T test setting)
       cpvarcol = NULL ,
       
       
       significant_col = "purple" , significant_alpha = 0.2,# only if type = signal
       wantbootplot = TRUE, 
       fun = samplemean <- function(x, d){return(mean(x[d]))},
       bootnum = 10,
       bootintval = c(.025,.975),
       bootalpha = 0.3 )+
        ylim(-10,10)

# type = signal ; multi = TRUE ; Have cpvar
mcplot(tests_rst = ERP_test,
       type = "signal", # type = "test" or "signal"
       multi = T,
       cor = FALSE, # only if type = test
       data = ERPdata , frames = 1:426 ,
       datacol = 2:427, subjcol = 430 , chancol = 1 , 
       othvarcol = c(428:429,431:432) , cpvarcol = 429 ,
       significant_col = "pink" , significant_alpha = 0.2,# only if type = signal
       wantbootplot = TRUE, 
       fun = samplemean <- function(x, d){return(mean(x[d]))},
       bootnum = 10,
       bootintval = c(.025,.975),
       bootalpha = 0.3 )+
        ylim(-10,10)

# type = signal ; multi = TRUE ; No cpvar
ERP_cor_test <- chan_test(ERPdata,2:427,chancol=1,testtype="erpfatest",         
            design_model=(~IQ+Condition),
            design0_model=(~Condition))

mcplot(tests_rst = ERP_cor_test,
       type = "signal",
       multi = T,
       cor = FALSE,
       data = ERPdata , frames = 1:426 ,
       datacol = 2:427, subjcol = 430 , chancol = 1 , 
       othvarcol = c(428:429,431:432) ,
       
       cpvarcol = NULL ,
       significant_col = "pink" , significant_alpha = 0.2,# only if type = signal
       wantbootplot = TRUE, 
       fun = samplemean <- function(x, d){return(mean(x[d]))},
       bootnum = 10,
       bootintval = c(.025,.975),
       bootalpha = 0.3 )

ERP only

1. scalpplot
2. topograph
1. scalpplot
revised from erpR package
plot the scalp :
BUT I think the bootplot is a better choice !!!!!
ERPdata_agg <- data_summarize(ERPdata,frames=1:426,2:427,430,1,othvarcol=c(428,429,431,432),
                          summarycol=c(428,429,1),
                          fun=mean)
scalpplot(ERPdata_agg,frames=1:426,erpcol=4:429,subcol=NULL,elecol=3,othvarcol = 1,
          cpvarcol=2)

2. topograph
revised from erpR
but I have not yet really understand the meaning of their setting.
ERP_word <- subset(ERPdata_agg,ERPdata_agg$Condition=="word")
topograph(ERP_word[,-c(1:2)], # you should unput ONLY the erpdata with electrode 
          frames  = 1:426,
          chcol = 1,
          startmsec=1, endmsec=426,
          win.ini=1,win.end=426,
          draw.nose=T,projection="equalarea")
WARNING: your data (after interpolation) are out of range as compared to the zlims specified.
 Your data range is: -8.25, 5.63 
 Your zlims are: -8, 8