content
stringlengths
0
14.9M
filename
stringlengths
44
136
#' Dataset: Orchard #' #' @description An experiment was carried out to analyze the treatments #' in orchards applied in the rows and between the rows, in a split-plot #' scheme according to a randomized block design. For this case, the line #' and leading are considered the levels of the factor applied in the plots #' and the treatments are considered the levels of the factor applied in #' the subplots. Microbial biomass carbon was analyzed. #' #' @docType data #' #' @usage data(orchard) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{A}}{Categorical vector with plot} #' \item{\code{B}}{Categorical vector with split-plot} #' \item{\code{Bloco}}{Categorical vector with block} #' \item{\code{Resp}}{Numeric vector with microbial biomass carbon} #' } #' @keywords datasets #' @seealso \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather}, \link{phao}, \link{passiflora}, \link{aristolochia} #' #' #' @examples #' data(orchard) "orchard"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/orchard_dataset.R
#' @keywords internal #' @md #' @name AgroR-package #' @docType package "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/package.R
#' Dataset: Substrate data in the production of passion fruit seedlings #' #' @description An experiment was carried out in order #' to evaluate the influence of the substrate on the #' dry mass of aerial part and root in yellow sour #' passion fruit. The experiment was conducted in a #' randomized block design with four replications. #' The treatments consisted of five substrates #' (Vermiculite, MC Normal, Carolina Soil, Mc organic #' and sand) #' #' @docType data #' #' @usage data(passiflora) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{trat}}{Categorical vector with substrate} #' \item{\code{bloco}}{Categorical vector with block} #' \item{\code{MSPA}}{Numeric vector with dry mass of aerial part} #' \item{\code{MSR}}{Numeric vector with dry mass of root} #' } #' @keywords datasets #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather} #' @examples #' data(passiflora) "passiflora"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/passiflora.R
#' Analysis: Principal components analysis #' #' @author Gabriel Danilo Shimizu #' @description This function performs principal component analysis. #' @return The eigenvalues and eigenvectors, the explanation percentages of each principal component, the correlations between the vectors with the principal components, as well as graphs are returned. #' @param data Data.frame with data set. Line name must indicate the treatment #' @param scale Performs data standardization (\emph{default} is TRUE) #' @param text Add label (\emph{default} is TRUE) #' @param pointsize Point size (\emph{default} is 5) #' @param textsize Text size (\emph{default} is 12) #' @param labelsize Label size (\emph{default} is 4) #' @param linesize Line size (\emph{default} is 0.8) #' @param repel Avoid text overlay (\emph{default} is TRUE) #' @param ylab Names y-axis #' @param xlab Names x-axis #' @param groups Define grouping #' @param sc Secondary axis scale ratio (\emph{default} is 1) #' @param font.family Font family (\emph{default} is sans) #' @param theme Theme ggplot2 (\emph{default} is theme_bw()) #' @param label.legend Legend title (when group is not NA) #' @param type.graph Type of chart (\emph{default} is biplot) #' @details #' #' The type.graph argument defines the graph that will be returned, #' in the case of "biplot" the biplot graph is returned with the #' first two main components and with eigenvalues and eigenvectors. #' In the case of "scores" only the treatment scores are returned, #' while for "cor" the correlations are returned. For "corPCA" a #' correlation between the vectors with the components is returned. #' #' @export #' @examples #' data(pomegranate) #' medias=tabledesc(pomegranate) #' PCA_function(medias) PCA_function=function(data, scale=TRUE, text=TRUE, pointsize=5, textsize=12, labelsize=4, linesize=0.6, repel=TRUE, ylab=NA, xlab=NA, groups=NA, sc=1, font.family="sans", theme=theme_bw(), label.legend="Cluster", type.graph="biplot"){ nVar = ncol(data) if(scale==TRUE){D=scale(data)}else{D=data} comp=length(colnames(D)) #fat=rep(c(-1,1),comp/2) Eig = eigen(var(D)) Avl = Eig$values#*fat Avt = Eig$vectors#*fat autov=data.frame(rbind(Eigenvalue=Avl, Perc=Avl/sum(Avl), CumPer=cumsum(Avl/sum(Avl)))) colnames(autov)=paste("PC",1:length(Avl),sep = "") if(is.na(xlab)==TRUE){xlab=paste("PC1 (",round(autov$PC1[2]*100,2),"%)",sep = "")} if(is.na(ylab)==TRUE){ylab=paste("PC2 (",round(autov$PC2[2]*100,2),"%)",sep = "")} # Avt[,1]=Avt[,1]*-1 Escores = as.matrix(D) %*% Avt Escores2 = apply(Escores, 2, function(x) (x - mean(x))/sd(x)) Escores2=data.frame(Escores2) colnames(Escores2)=paste("PC",1:ncol(Escores2),sep = "") rownames(Escores2)=rownames(data) Escores2=Escores2*sc setas=cor(D,Escores2) setas=data.frame(setas) requireNamespace("ggplot2") if(is.na(groups[1])==TRUE){groups=NA}else{groups=as.factor(groups)} if(type.graph=="biplot"){ if(is.na(groups[1])==TRUE){ PC1=Escores2$PC1 PC2=Escores2$PC2 graph=ggplot(Escores2,aes(y=PC2,x=PC1))+ geom_point(data=Escores2,aes(y=PC2,x=PC1), shape=21,color="black",fill="gray",size=pointsize)} if(is.na(groups[1])==FALSE){ PC1=Escores2$PC1 PC2=Escores2$PC2 graph=ggplot(Escores2,aes(y=PC2,x=PC1))+ geom_point(data=Escores2,aes(y=PC2,x=PC1,groups=groups,fill=groups), shape=21,color="black",size=pointsize)+labs(fill=label.legend)} graph=graph+theme+ geom_vline(xintercept = 0,lty=2,size=linesize)+ geom_hline(yintercept = 0,lty=2,size=linesize)+ geom_segment(data=setas,aes(x=0,y=0, yend=PC2, xend=PC1),size=linesize, arrow = arrow(length = unit(0.14,"inches")))+ theme(axis.text = element_text(size=textsize,color="black",family=font.family), legend.text = element_text(size=textsize,family=font.family), legend.title = element_text(size=textsize,family=font.family), axis.title = element_text(size=textsize,color="black",family=font.family))+ xlab(xlab)+ylab(ylab) if(repel==FALSE){ if(text==TRUE){ graph=graph+ geom_text(data=Escores2,aes(label=rownames(Escores2)),color="black",family=font.family,size=labelsize)} graph=graph+geom_text(data=setas,aes(label=rownames(setas)),color="black",family=font.family,size=labelsize)} else{requireNamespace("ggrepel") if(text==TRUE){graph=graph+ geom_text_repel(data=Escores2,aes(label=rownames(Escores2)),color="black",family=font.family,size=labelsize)} graph=graph+geom_text_repel(data=setas,aes(label=rownames(setas)),color="black",family=font.family,size=labelsize)}} if(type.graph=="scores"){ if(is.na(groups[1])==TRUE){ PC1=Escores2$PC1 PC2=Escores2$PC2 graph=ggplot(Escores2,aes(y=PC2,x=PC1))+ geom_point(data=Escores2,aes(y=PC2,x=PC1), shape=21,color="black",fill="gray",size=pointsize)} if(is.na(groups[1])==FALSE){ graph=ggplot(Escores2,aes(y=PC2,x=PC1))+ geom_point(data=Escores2,aes(y=PC2,x=PC1,groups=groups,fill=groups), shape=21,color="black",size=pointsize)+labs(fill=label.legend)} graph=graph+theme+ geom_vline(xintercept = 0,lty=2,size=linesize)+ geom_hline(yintercept = 0,lty=2,size=linesize)+ theme(axis.text = element_text(size=textsize,color="black",family=font.family), legend.text = element_text(size=textsize,family=font.family), legend.title = element_text(size=textsize,family=font.family), axis.title = element_text(size=textsize,color="black",family=font.family))+ xlab(xlab)+ylab(ylab) if(repel==FALSE & text==TRUE){ graph=graph+ geom_text(data=Escores2,aes(label=rownames(Escores2)),color="black",family=font.family,size=labelsize)} else{if(text==TRUE){requireNamespace("ggrepel") graph=graph+ geom_text_repel(data=Escores2,aes(label=rownames(Escores2)),color="black",family=font.family,size=labelsize)}}} if(type.graph=="cor"){ circle <- function(center = c(0, 0), npoints = 100) { r = 1 tt = seq(0, 2 * pi, length = npoints) xx = center[1] + r * cos(tt) yy = center[1] + r * sin(tt) x=xx y=yy return(data.frame(x = xx, y = yy)) } corcir = circle(c(0, 0), npoints = 100) x=corcir$x y=corcir$y graph=ggplot()+theme+ geom_vline(xintercept = 0,lty=2,size=linesize)+ geom_hline(yintercept = 0,lty=2,size=linesize)+ geom_segment(data=setas,aes(x=0,y=0, yend=PC2, xend=PC1),size=linesize, arrow = arrow(length = unit(0.14,"inches")))+ theme(axis.text = element_text(size=textsize,color="black",family=font.family), legend.text = element_text(size=textsize,family=font.family), legend.title = element_text(size=textsize,family=font.family), axis.title = element_text(size=textsize,color="black",family=font.family))+ xlab(xlab)+ylab(ylab)+ geom_path(data = corcir, aes(x = x, y = y), colour = "gray65") if(repel==FALSE & text==TRUE){ PC1=setas$PC1 PC2=setas$PC2 graph=graph+ geom_text(data=setas,aes(y=PC2,x=PC1,label=rownames(setas)), color="black",family=font.family,size=labelsize)} else{if(text==TRUE){requireNamespace("ggrepel") graph=graph+ geom_text_repel(data=setas,aes(y=PC2,x=PC1,label=rownames(setas)), color="black",family=font.family,size=labelsize)}}} autovetor=Eig$vectors colnames(autovetor)=colnames(autov) rownames(autovetor)=rownames(setas) colnames(Escores)=colnames(autov) if(type.graph=="screeplot"){ dados=data.frame(t(autov)) Perc=dados$Perc graph=ggplot(data=dados,aes(x=rownames(dados),y=Perc,group=1))+ geom_col(fill="blue",color="black")+ theme(axis.text = element_text(size=textsize,color="black",family=font.family), legend.text = element_text(size=textsize,family=font.family), legend.title = element_text(size=textsize,family=font.family), axis.title = element_text(size=textsize,color="black",family=font.family))+ geom_point(size=3,color="red")+geom_line(color="red",size=linesize)+theme+ xlab("Dimensions")+ylab("Percentage of explained variances") } if(type.graph=="corPCA"){ cor=as.vector(unlist(setas)) Var1=rep(rownames(setas),ncol(setas)) Var2=rep(colnames(setas), e=nrow(setas)) dados=data.frame(Var1,Var2,cor) graph=ggplot(dados,aes(x=Var2, y=Var1, fill=cor))+ geom_tile(color="gray50",size=1)+ scale_x_discrete(position = "top")+ scale_fill_distiller(palette = "RdBu",direction = 1,limits=c(-1,1))+ geom_label(aes(label=format(cor,digits=2)), fill="lightyellow",label.size = 1)+ ylab("")+xlab("")+ labs(fill="Correlation")+ theme(axis.text = element_text(size=textsize,color="black",family=font.family), axis.title = element_text(size=textsize,color="black",family=font.family), legend.text = element_text(size=textsize,family=font.family), legend.title = element_text(size=textsize,family=font.family), legend.position = "right", axis.ticks = element_blank(), panel.background = element_blank(), panel.grid.major = element_blank(), panel.grid.minor = element_blank()) } #print(graph) list(Eigenvalue=autov, "Eigenvector"=autovetor, "Scores PCs"=Escores, "Correlation var x PC"=setas, graph=graph)}
/scratch/gouwar.j/cran-all/cranData/AgroR/R/pca_function.R
#' Dataset: Pepper #' #' @description A vegetable breeder is characterizing five mini pepper #' accessions from the State University of Londrina germplasm bank for #' agronomic and biochemical variables. The experiment was conducted in #' a completely randomized design with four replications #' @docType data #' #' @usage data(pepper) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{Acesso}}{Categorical vector with accessions} #' \item{\code{MS}}{Numeric vector com dry mass} #' \item{\code{VitC}}{Numeric vector with Vitamin C} #' } #' @keywords datasets #' @seealso \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather}, \link{phao}, \link{passiflora}, \link{aristolochia} #' #' #' @examples #' data(pepper) "pepper"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/pepper_dataset.R
#' Dataset: Osmocote in \emph{Phalaenopsis} sp. #' #' The objective of the work was to evaluate the #' effect of doses of osmocote (15-09-12-N-P2O5-K2O, #' respectively) on the initial development of the #' orchid \emph{Phalaenopsis} sp. The osmocote fertilizer #' was added in the following doses: 0, 2, 4, 6 and #' 8 g vase-1. After twelve months, leaf length was #' evaluated. #' #' @docType data #' #' @usage data(phao) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{dose}}{Numeric vector with doses} #' \item{\code{comp}}{Numeric vector with leaf length} #' } #' @seealso \link{pomegranate}, \link{passiflora}, \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather} #' @references de Paula, J. C. B., Junior, W. A. R., Shimizu, G. D., Men, G. B., & de Faria, R. T. (2020). Fertilizante de liberacao controlada no crescimento inicial da orquidea \emph{Phalaenopsis} sp. Revista Cultura Agronomica, 29(2), 289-299. #' @keywords datasets #' #' @examples #' data(phao) "phao"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/phao.R
#' Graph: Climate chart of temperature and humidity (Model 2) #' #' @description The plot_TH1 function allows the user to build a column/line graph with climatic parameters of temperature (maximum, minimum and average) and relative humidity (UR) or precipitation. This chart is widely used in scientific work in agrarian science #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param tempo Vector with times #' @param Tmed Vector with mean temperature #' @param Tmax Vector with maximum temperature #' @param Tmin Vector with minimum temperature #' @param UR Vector with relative humidity or precipitation #' @param xlab x axis name #' @param yname1 y axis name #' @param yname2 Secondary y-axis name #' @param legend.T faceted title legend 1 #' @param legend.H faceted title legend 2 #' @param legend.tmed Legend mean temperature #' @param legend.tmin Legend minimum temperature #' @param legend.tmax Legend maximum temperature #' @param facet.fill faceted title fill color (\emph{default} is #FF9933) #' @param panel.grid remove grid line (\emph{default} is FALSE) #' @param x x scale type (days or data, default is "days") #' @param breaks Range for x scale when x = "date" (default is 1 months) #' @param textsize Axis text size #' @param legendsize Legend text size #' @param titlesize Axis title size #' @param linesize Line size #' @param date_format Date format for x="data" #' @param legend.position Legend position #' @param colormax Maximum line color (\emph{default} is "red") #' @param colormin Minimum line color (\emph{default} is "blue") #' @param colormean Midline color (\emph{default} is "darkgreen") #' @param fillarea area fill color (\emph{default} is "darkblue") #' @param angle x-axis scale text rotation #' @return Returns row and column graphs for graphical representation of air temperature and relative humidity. Graph normally used in scientific articles #' @seealso \link{radargraph}, \link{sk_graph}, \link{barplot_positive}, \link{corgraph}, \link{spider_graph}, \link{line_plot} #' @export #' @examples #' library(AgroR) #' data(weather) #' with(weather, plot_TH1(tempo, Tmed, Tmax, Tmin, UR)) plot_TH1=function(tempo, Tmed, Tmax, Tmin, UR, xlab="Time", yname1=expression("Humidity (%)"), yname2=expression("Temperature ("^o*"C)"), legend.T="Temperature", legend.H="Humidity", legend.tmed="Tmed", legend.tmin="Tmin", legend.tmax="Tmax", colormax="red", colormin="blue", colormean="darkgreen", fillarea="darkblue", facet.fill="#FF9933", panel.grid=FALSE, x="days", breaks="1 months", textsize=12, legendsize=12, titlesize=12, linesize=1, date_format="%m-%Y", angle=0, legend.position=c(0.1,0.3)){ data=data.frame(tempo,Tmed,Tmax,Tmin,UR) requireNamespace("ggplot2") if(x=="days"){ a=ggplot(data, aes(x = tempo)) + geom_line(aes(y = Tmed,color=legend.tmed),size=linesize)+ geom_line(aes(y = Tmin,color=legend.tmin),size=linesize)+ geom_line(aes(y = Tmax,color=legend.tmax),size=linesize)+ scale_colour_manual(values = c(colormax,colormean,colormin))+ theme_bw()+ labs(x=xlab,y=yname2,color="")+ facet_wrap(~as.character(legend.T))+ theme(axis.text.y = element_text(size=textsize, color="black"), axis.text.x = element_blank(), strip.text = element_text(size=13), strip.background = element_rect(fill=facet.fill), axis.title.x = element_blank(), legend.position = legend.position, legend.text = element_text(size=legendsize,hjust = 0)) b=ggplot(data,aes(x=tempo))+ geom_area(aes(y=UR),fill=fillarea)+ theme_bw()+ labs(x=xlab,y=yname1,color="")+ facet_wrap(~as.character(legend.H))+ theme(axis.text = element_text(size=textsize, color="black"), axis.text.x = element_text(angle=angle), strip.text = element_text(size=13), strip.background = element_rect(fill=facet.fill), axis.title.x = element_text(size=titlesize), legend.position = legend.position, legend.text = element_text(size=legendsize))} if(x=="data"){ a=ggplot(data, aes(x = tempo)) + scale_x_datetime(breaks=breaks,labels = date_format(date_format)) + geom_line(aes(y = Tmed,color=legend.tmed),size=linesize)+ geom_line(aes(y = Tmin,color=legend.tmin),size=linesize)+ geom_line(aes(y = Tmax,color=legend.tmax),size=linesize)+ scale_colour_manual(values = c(colormax,colormean,colormin))+ theme_bw()+ labs(y=yname2,y=ylab,color="")+ facet_wrap(~as.character(legend.T))+ theme(axis.text.y = element_text(size=textsize, color="black"), axis.text.x = element_blank(), axis.title.x = element_blank(), strip.text = element_text(size=13), legend.position = legend.position, legend.text = element_text(size=legendsize,hjust = 0)) b=ggplot(data,aes(x=tempo))+ geom_area(aes(y=UR),fill=fillarea)+ theme_bw()+ labs(x=xlab,y=yname1)+ facet_wrap(~as.character(legend.H))+ theme(axis.text = element_text(size=textsize, color="black"), strip.text = element_text(size=13), axis.text.x = element_text(angle=angle), axis.title = element_text(size=titlesize), legend.position = legend.position, legend.text = element_text(size=legendsize))} if(panel.grid==FALSE){ a=a+theme(panel.grid = element_blank()) b=b+theme(panel.grid = element_blank())} cowplot::plot_grid(a,b,ncol=1,align = "v",rel_heights = c(3/5,2/5)) # print(grafico) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/plot_TH1_function.R
#' Graph: Climate chart of temperature and humidity #' #' @description The plot_TH function allows the user to build a column/line graph with climatic parameters of temperature (maximum, minimum and average) and relative humidity (UR) or precipitation. This chart is widely used in scientific work in agrarian science #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param tempo Vector with times #' @param Tmed Vector with mean temperature #' @param Tmax Vector with maximum temperature #' @param Tmin Vector with minimum temperature #' @param UR Vector with relative humidity or precipitation #' @param xlab x axis name #' @param yname1 y axis name #' @param yname2 Secondary y-axis name #' @param legend.H Legend column #' @param legend.tmed Legend mean temperature #' @param legend.tmin Legend minimum temperature #' @param legend.tmax Legend maximum temperature #' @param x x scale type (days or data, default is "days") #' @param breaks Range for x scale when x = "date" (default is 1 months) #' @param textsize Axis text size #' @param legendsize Legend text size #' @param titlesize Axis title size #' @param linesize Line size #' @param date_format Date format for x="data" #' @param sc Scale for secondary y-axis in relation to primary y-axis (declare the number of times that y2 is less than or greater than y1, the default being 2.5) #' @param legend.position Legend position #' @param theme ggplot2 theme #' @param colormax Maximum line color (\emph{default} is "red") #' @param colormin Minimum line color (\emph{default} is "blue") #' @param colormean Midline color (\emph{default} is "darkgreen") #' @param fillbar Column fill color (\emph{default} is "gray80") #' @param limitsy1 Primary y-axis scale (\emph{default} is c(0,100)) #' @param angle x-axis scale text rotation #' @return Returns row and column graphs for graphical representation of air temperature and relative humidity. Graph normally used in scientific articles #' @seealso \link{radargraph}, \link{sk_graph}, \link{barplot_positive}, \link{corgraph}, \link{plot_TH1}, \link{spider_graph}, \link{line_plot} #' @export #' @examples #' library(AgroR) #' data(weather) #' with(weather, plot_TH(tempo, Tmed, Tmax, Tmin, UR)) plot_TH=function(tempo, Tmed, Tmax, Tmin, UR, xlab="Time", yname1=expression("Humidity (%)"), yname2=expression("Temperature ("^o*"C)"), legend.H="Humidity", legend.tmed="Tmed", legend.tmin="Tmin", legend.tmax="Tmax", colormax="red", colormin="blue", colormean="darkgreen", fillbar="gray80", limitsy1=c(0,100), x="days", breaks="1 months", textsize=12, legendsize=12, titlesize=12, linesize=1, date_format="%m-%Y", sc=2.5, angle=0, legend.position="bottom", theme=theme_classic()){ data=data.frame(tempo,Tmed,Tmax,Tmin,UR) requireNamespace("ggplot2") #requireNamespace("scales") # Dados completos if(is.na(Tmed[1])==FALSE && is.na(Tmin[1])==FALSE && is.na(Tmax[1])==FALSE && is.na(UR[1])==FALSE){ if(x=="days"){ a=ggplot(data, aes(x = tempo)) + geom_col(aes(y = UR, fill=legend.H))+ scale_x_continuous() + scale_y_continuous(sec.axis = sec_axis(~ . *1 ))+ geom_line(aes(y = Tmed*sc,color=legend.tmed),size=linesize)+ geom_line(aes(y = Tmin*sc,color=legend.tmin),size=linesize)+ geom_line(aes(y = Tmax*sc,color=legend.tmax),size=linesize)+ scale_y_continuous(sec.axis = sec_axis(~ . /sc,name = yname2), limits = limitsy1,name=yname1)+ scale_colour_manual(values = c(colormax,colormean,colormin))+ scale_fill_manual(values = fillbar)+labs(fill="",color="") grafico=a} if(x=="data"){ b=ggplot(data, aes(x = tempo)) + geom_col(aes(y = UR, fill=legend.H))+ scale_x_datetime(breaks=breaks,labels = date_format(date_format)) + scale_y_continuous(sec.axis = sec_axis(~ . *1 ))+ geom_line(aes(y = Tmed*sc,color=legend.tmed),size=linesize)+ geom_line(aes(y = Tmin*sc,color=legend.tmin),size=linesize)+ geom_line(aes(y = Tmax*sc,color=legend.tmax),size=linesize)+ scale_y_continuous(sec.axis = sec_axis(~ . /sc,name = yname2), limits = limitsy1,name=yname1)+ scale_colour_manual(values = c(colormax,colormean,colormin))+ scale_fill_manual(values = fillbar)+labs(fill="",color="") grafico=b}} if(is.na(Tmed[1])==FALSE && is.na(Tmin[1])==TRUE && is.na(Tmax[1])==TRUE && is.na(UR[1])==TRUE){ if(x=="days"){ a=ggplot(data, aes(x = tempo)) + scale_x_continuous() + geom_line(aes(y = Tmed*sc,color=legend.tmed),size=linesize,show.legend = F)+ labs(color="",y=yname2) grafico=a} if(x=="data"){ b=ggplot(data, aes(x = tempo)) + scale_x_datetime(breaks=breaks, labels = date_format(date_format)) + geom_line(aes(y = Tmed*sc,color=legend.tmed),show.legend = FALSE,size=linesize)+ labs(fill="",y=yname2) grafico=b}} # Sem UR if(is.na(Tmed[1])==FALSE && is.na(Tmin[1])==FALSE && is.na(Tmax[1])==FALSE && is.na(UR[1])==TRUE){ if(x=="days"){ a=ggplot(data, aes(x = tempo)) +scale_x_continuous() + scale_y_continuous(name=yname2)+ geom_line(aes(y = Tmed,color=legend.tmed),size=linesize)+ geom_line(aes(y = Tmin,color=legend.tmin),size=linesize)+ geom_line(aes(y = Tmax,color=legend.tmax),size=linesize)+ scale_colour_manual(values = c(colormax,colormean,colormin))+ labs(color="") grafico=a} if(x=="data"){ b=ggplot(data, aes(x = tempo)) + scale_x_datetime(breaks=breaks,labels = date_format(date_format)) + scale_y_continuous(name=yname2)+ geom_line(aes(y = Tmed,color=legend.tmed),size=linesize)+ geom_line(aes(y = Tmin,color=legend.tmin),size=linesize)+ geom_line(aes(y = Tmax,color=legend.tmax),size=linesize)+ scale_colour_manual(values = c(colormax,colormean,colormin))+ labs(color="") grafico=b}} # Sem T medio if(is.na(Tmed[1])==TRUE && is.na(Tmin[1])==FALSE && is.na(Tmax[1])==FALSE && is.na(UR[1])==FALSE){ if(x=="days"){ a=ggplot(data, aes(x = tempo)) + geom_col(aes(y = UR, fill=legend.H))+scale_x_continuous() + scale_y_continuous(sec.axis = sec_axis(~ . *1 ))+ geom_line(aes(y = Tmin*sc,color=legend.tmin),size=linesize)+ geom_line(aes(y = Tmax*sc,color=legend.tmax),size=linesize)+ scale_y_continuous(sec.axis = sec_axis(~ . /sc,name = yname2), limits = limitsy1,name=yname1)+ scale_colour_manual(values = c(colormax,colormin))+ scale_fill_manual(values = fillbar)+labs(fill="",color="") grafico=a} if(x=="data"){ b=ggplot(data, aes(x = tempo)) + geom_col(aes(y = UR, fill=legend.H))+ scale_x_datetime(breaks=breaks, labels = date_format(date_format)) + scale_y_continuous(sec.axis = sec_axis(~ . *1 ))+ geom_line(aes(y = Tmin*sc,color=legend.tmin),size=linesize)+ geom_line(aes(y = Tmax*sc,color=legend.tmax),size=linesize)+ scale_y_continuous(sec.axis = sec_axis(~ . /sc,name = yname2), limits = limitsy1,name=yname1)+ scale_colour_manual(values = c(colormax,colormin))+ scale_fill_manual(values = fillbar)+labs(fill="",color="") grafico=b}} # Com medio e sem maximo/minimo if(is.na(Tmed[1])==FALSE && is.na(Tmin[1])==TRUE && is.na(Tmax[1])==TRUE && is.na(UR[1])==FALSE){ if(x=="days"){ a=ggplot(data, aes(x = tempo)) + geom_col(aes(y = UR, fill=legend.H))+scale_x_continuous() + scale_y_continuous(sec.axis = sec_axis(~ . *1 ))+ geom_line(aes(y = Tmed*sc,color=legend.tmed),size=linesize)+ scale_y_continuous(sec.axis = sec_axis(~ . /sc,name = yname2), limits = limitsy1,name=yname1)+ scale_colour_manual(values = colormean)+ scale_fill_manual(values = fillbar)+labs(fill="",color="") grafico=a} if(x=="data"){ b=ggplot(data, aes(x = tempo)) + geom_col(aes(y = UR, fill=legend.H))+ scale_x_datetime(breaks=breaks, labels = date_format(date_format)) + scale_y_continuous(sec.axis = sec_axis(~ . *1 ))+ geom_line(aes(y = Tmed*sc,color=legend.tmed),size=linesize)+ scale_y_continuous(sec.axis = sec_axis(~ . /sc,name = yname2), limits = limitsy1,name=yname1)+ scale_colour_manual(values = colormean)+ scale_fill_manual(values = fillbar)+labs(fill="",color="") grafico=b}} graficos=list(grafico+ theme+labs(x=xlab)+ theme(axis.text = element_text(size=textsize, color="black"), axis.text.x = element_text(angle=angle), axis.title = element_text(size=titlesize), legend.position = legend.position, legend.text = element_text(size=legendsize)))[[1]] print(graficos) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/plot_TH_function.R
#' Graph: Interaction plot #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @description Performs an interaction graph from an output of the FAT2DIC, FAT2DBC, PSUBDIC or PSUBDBC commands. #' @param a FAT2DIC, FAT2DBC, PSUBDIC or PSUBDBC object #' @param repel a boolean, whether to use ggrepel to avoid overplotting text labels or not. #' @param pointsize Point size #' @param linesize Line size (Trendline and Error Bar) #' @param box_label Add box in label #' @param width.bar width of the error bars. #' @param add.errorbar Add error bars. #' @export #' @import ggplot2 #' @importFrom crayon green #' @importFrom crayon bold #' @importFrom crayon italic #' @importFrom crayon red #' @importFrom crayon blue #' @import stats #' @return Returns an interaction graph with averages and letters from the multiple comparison test #' @examples #' data(cloro) #' a=with(cloro, FAT2DIC(f1, f2, resp)) #' plot_interaction(a) plot_interaction=function(a, box_label=TRUE, repel=FALSE, pointsize=3, linesize=0.8, width.bar=0.05, add.errorbar=TRUE){ data=a[[2]] requireNamespace("ggplot2") graph=ggplot(data$data, aes(x=data$data[,1], y=data$data$media, color=data$data[,2], group=data$data[,2]))+ geom_point(show.legend = TRUE, size=pointsize) if(add.errorbar==TRUE){ graph=graph+ geom_errorbar(aes(ymax=data$data$media+data$data$desvio, ymin=data$data$media-data$data$desvio), width=width.bar,size=linesize)} graph=graph+ geom_line(size=linesize) if(isTRUE(repel)==FALSE & box_label==TRUE){ graph=graph+ geom_label(aes(label=data$data$numero),show.legend = FALSE,family=a[[2]]$plot$family)} if(isTRUE(repel)==TRUE & box_label==TRUE){ requireNamespace("ggrepel") graph=graph+ geom_label_repel(aes(label=data$data$numero),show.legend = FALSE,family=a[[2]]$plot$family)} if(isTRUE(repel)==FALSE & box_label==FALSE){ graph=graph+ geom_text(aes(label=data$data$numero),show.legend = FALSE,family=a[[2]]$plot$family)} if(isTRUE(repel)==TRUE & box_label==FALSE){ requireNamespace("ggrepel") graph=graph+ geom_text_repel(aes(label=data$data$numero),show.legend = FALSE)} graph=graph+data$theme+ labs(caption=data$labels$caption, color=data$labels$fill, x=data$labels$x, y=data$labels$y) print(graph) graphs=list(graph) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/plot_interaction_function.R
#' Graphics: Graphic for t test to compare means with a reference value #' #' @description Sometimes the researcher wants to test whether the treatment mean is greater than/equal to or less than a reference value. For example, I want to know if the average productivity of my treatment is higher than the average productivity of a given country. For this, this function allows comparing the means with a reference value using the t test. #' @author Gabriel Danilo Shimizu #' @param tonetest t.one.test object #' @param alpha confidence level. #' #' @export #' @return returns a density plot and a column plot to compare a reference value with other treatments. #' @examples #' library(AgroR) #' data("pomegranate") #' resu=tonetest(resp=pomegranate$WL, trat=pomegranate$trat, mu=2) #' plot_tonetest(resu) plot_tonetest=function(tonetest,alpha=0.95){ xp=as.list(1:length(tonetest$min)) resp=as.list(1:length(tonetest$min)) for(i in 1:length(tonetest$min)){ xp1=seq(tonetest$mean[i]-5*tonetest$sd[i], tonetest$mean[i]+5*tonetest$sd[i],length=500) yp=dnorm(xp1,mean = tonetest$mean[i],sd = tonetest$sd[i]) resp[[i]]=yp xp[[i]]=xp1} names(resp)=names(tonetest$min) data=data.frame(xp=unlist(xp),yp=unlist(resp),trat=rep(names(resp),e=500)) a=ggplot(data,aes(x=xp,y=yp,fill=trat))+labs(fill="",x="Response",y="Density")+ geom_polygon(color="black",alpha=0.3)+ theme_classic()+ geom_vline(xintercept = tonetest$mean.ref,lty=2,size=3,alpha=0.3)+ theme(axis.text = element_text(size=12),legend.position = c(0.9,0.8)) media=c();trat=c() b=ggplot(data.frame(media=tonetest$mean,trat=names(tonetest$mean)))+ geom_col(aes(x=trat,y=media,fill=trat),show.legend = FALSE, color="black")+ theme_classic()+labs(x="",y="Response")+ geom_hline(yintercept = tonetest$mean.ref,lty=2,size=3,alpha=0.3)+ theme(axis.text = element_text(size=12)) if(tonetest$conf.inf[1]!=-Inf & tonetest$conf.sup[1]!=Inf){ b=b+geom_errorbar(aes(ymin=tonetest$conf.inf, ymax=tonetest$conf.sup,x=trat),width=0.2)+ geom_text(aes(x=trat, y=tonetest$conf.sup+0.1*media, label=ifelse(tonetest$p.value<1-alpha,"*","ns")),size=5)} if(tonetest$conf.inf[1]==-Inf){ b=b+geom_errorbar(aes(ymin=media, ymax=tonetest$conf.sup,x=trat),width=0.2)+ geom_text(aes(x=trat, y=tonetest$conf.sup+0.1*media, label=ifelse(tonetest$p.value<1-alpha,"*","ns")),size=5)} if(tonetest$conf.sup[1]==Inf){ b=b+geom_errorbar(aes(ymin=tonetest$conf.inf, ymax=media,x=trat),width=0.2)+ geom_text(aes(x=trat, y=media+0.1*media, label=ifelse(tonetest$p.value<1-alpha,"*","ns")),size=5)} gridExtra::grid.arrange(a,b,ncol=2) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/plot_tonetest.R
#' Graph: Plot correlation #' @description Correlation analysis function (Pearson or Spearman) #' @param x Numeric vector with independent variable #' @param y Numeric vector with dependent variable #' @param method Method correlation (\emph{default} is Pearson) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param pointsize Point size #' @param shape shape format #' @param fill Fill point #' @param color Color point #' @param axis.size Axis text size #' @param ic add interval of confidence #' @param title title #' @param family Font family #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @return The function returns a graph for correlation #' @export #' @examples #' data("pomegranate") #' with(pomegranate, plot_cor(WL, SS, xlab="WL", ylab="SS")) plot_cor=function(x,y, method="pearson", ylab="Dependent", xlab="Independent", theme=theme_classic(), pointsize=5, shape=21, fill="gray", color="black", axis.size=12, ic=TRUE, title=NA, family="sans"){ if(is.na(title)==TRUE){ if(method=="pearson"){title="Pearson correlation"} if(method=="spearman"){title="Spearman correlation"} } if(method=="pearson"){corre=cor(y,x) pvalor=cor.test(y,x,method="pearson",exact=FALSE)$p.value} if(method=="spearman"){corre=cor(y,x,method = "spearman") pvalor=cor.test(y,x,method="spearman",exact=FALSE)$p.value} requireNamespace("ggplot2") data=data.frame(y,x) ggplot(data,aes(y=y,x=x))+ geom_point(shape=shape,fill=fill,color=color,size=pointsize)+ geom_smooth(color=color,method = "lm")+ theme+labs(title=title,x=xlab,y=ylab)+ theme(axis.text = element_text(size=axis.size, color="black",family = family), axis.title = element_text(family = family))+ annotate(geom = "text",x = -Inf,y=Inf, label=paste("R = ", round(corre,2), ", p-value =", format(round(pvalor,3),scientific = TRUE),sep = ""), hjust = -0.1, vjust = 1.1) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/plotcor_function.R
#' Graph: Column, box or segment chart with observations #' #' @description The function performs the construction of graphs of boxes, columns or segments with all the observations represented in the graph. #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param model DIC, DBC or DQL object #' @export #' @return Returns with graph of boxes, columns or segments with all the observations represented in the graph. #' @examples #' data("pomegranate") #' a=with(pomegranate,DIC(trat,WL,geom="point")) #' plot_jitter(a) plot_jitter=function(model){ a=model requireNamespace("ggplot2") if(a[[1]]$plot$geom=="bar"){ data=a[[1]]$data if(colnames(data)[3]=="respO"){ data=data[,-1] colnames(data)[2]="resp"} sup=a[[1]]$plot$sup resp=a[[1]]$plot$response trat=a[[1]]$plot$trat fill=a[[1]]$plot$fill theme=a[[1]]$plot$theme ylab=a[[1]]$plot$ylab xlab=a[[1]]$plot$xlab cap=a[[1]]$labels$caption textsize=a[[1]]$plot$textsize media=data$media desvio=data$desvio limite=data$limite letra=data$limite graph=ggplot(data,aes(y=media,x=rownames(data)))+ geom_col(fill=fill,color="black")+ theme+ geom_text(aes(y=limite+sup,label=letra))+ labs(x=xlab,y=ylab,caption = cap)+ geom_jitter(data=data.frame(trat,resp), aes(y=resp,x=trat),size=2, color="gray10", width = 0.1, alpha = 0.2)+ geom_errorbar(aes(ymax=media+desvio, ymin=media-desvio),width=0.3)+ theme(axis.text=element_text(size = textsize, color="black")) print(graph) } if(a[[1]]$plot$geom=="point"){ data=a[[1]]$data if(colnames(data)[3]=="respO"){ data=data[,-1] colnames(data)[2]="resp"} sup=a[[1]]$plot$sup resp=a[[1]]$plot$response trat=a[[1]]$plot$trat fill=a[[1]]$plot$fill theme=a[[1]]$plot$theme ylab=a[[1]]$plot$ylab xlab=a[[1]]$plot$xlab cap=a[[1]]$labels$caption textsize=a[[1]]$plot$textsize media=data$media desvio=data$desvio limite=data$limite letra=data$limite graph=ggplot(data,aes(y=media,x=rownames(data)))+ theme+ geom_text(aes(y=limite+sup,label=letra))+ labs(x=xlab,y=ylab,caption = cap)+ geom_jitter(data=data.frame(trat,resp), aes(y=resp,x=trat),size=2, color="gray10", width = 0.1, alpha = 0.2)+ geom_errorbar(aes(ymax=media+desvio, ymin=media-desvio),width=0.3)+ geom_point(fill=fill,color="black",shape=21,size=5)+ theme(axis.text=element_text(size = textsize, color="black")) graph } if(a[[1]]$plot$geom=="box"){ data1=a[[1]]$data response=data1$response trat=data1$trat sup=a[[1]]$plot$sup data=a[[1]]$plot$dadosm2 if(colnames(data)[3]=="respO"){ data=data[,-1] colnames(data)[2]="resp"} resp=a[[1]]$plot$response trat=a[[1]]$plot$trat fill=a[[1]]$plot$fill theme=a[[1]]$plot$theme ylab=a[[1]]$plot$ylab xlab=a[[1]]$plot$xlab cap=a[[1]]$labels$caption textsize=a[[1]]$plot$textsize media=data$media desvio=data$desvio limite=data$limite letra=data$limite superior=data$superior graph=ggplot(data1,aes(y=response,x=trat))+ geom_boxplot(fill=fill,color="black",outlier.color = NA)+ theme+ geom_text(data=data,aes(y=superior, x=rownames(data), label=letra))+ labs(x=xlab,y=ylab,caption = cap)+ geom_jitter(aes(y=resp,x=trat),size=2, color="gray10", width = 0.1, alpha = 0.2)+ theme(axis.text=element_text(size = textsize, color="black")) # print(graph) graph } graph }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/plotjitter_function.R
#' Analysis: Linear regression graph in double factorial #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @description Linear regression analysis for significant interaction of an experiment with two factors, one quantitative and one qualitative #' @param fator1 Numeric or complex vector with factor 1 levels #' @param resp Numerical vector containing the response of the experiment. #' @param fator2 Numeric or complex vector with factor 2 levels #' @param color Graph color (\emph{default} is NA) #' @param grau Degree of the polynomial (1,2 or 3) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param se Adds confidence interval (\emph{default} is FALSE) #' @param legend.title Title legend #' @param textsize Font size (\emph{default} is 12) #' @param family Font family (\emph{default} is sans) #' @param point Defines whether to plot all points ("all"), mean ("mean"), mean with standard deviation (\emph{default} - "mean_sd") or mean with standard error ("mean_se"). #' @param ylim y-axis scale #' @param posi Legend position #' @param width.bar width of the error bars of a regression graph. #' @param pointsize Point size (\emph{default} is 4) #' @param linesize line size (Trendline and Error Bar) #' @param separate Separation between treatment and equation (\emph{default} is c("(\"","\")")) #' @param n Number of decimal places for regression equations #' @param SSq Sum of squares of the residue #' @param DFres Residue freedom degrees #' @keywords regression #' @keywords Experimental #' @seealso \link{polynomial}, \link{polynomial2_color} #' @return Returns two or more linear, quadratic or cubic regression analyzes. #' @export #' @examples #' dose=rep(c(0,0,0,2,2,2,4,4,4,6,6,6),3) #' resp=c(8,7,5,23,24,25,30,34,36,80,90,80, #' 12,14,15,23,24,25,50,54,56,80,90,40, #' 12,14,15,3,4,5,50,54,56,80,90,40) #' trat=rep(c("A","B","C"),e=12) #' polynomial2(dose, resp, trat, grau=c(1,2,3)) polynomial2=function(fator1, resp, fator2, color=NA, grau=NA, ylab="Response", xlab="Independent", theme=theme_classic(), se=FALSE, point="mean_sd", legend.title="Treatments", posi="top", textsize=12, ylim=NA, family="sans", width.bar=NA, pointsize=3, linesize=0.8, separate=c("(\"","\")"), n=NA, DFres=NA, SSq=NA){ if(is.na(width.bar)==TRUE){width.bar=0.05*mean(fator1)} requireNamespace("crayon") requireNamespace("ggplot2") anovaquali=anova(aov(resp~as.factor(fator1)*fator2)) Fator2=fator2=as.factor(fator2) if(is.na(color)[1]==TRUE){color=1:length(levels(Fator2))} if(is.na(grau)[1]==TRUE){grau=rep(1,length(levels(Fator2)))} curvas=c() texto=c() desvios=c() data=data.frame(fator1,fator2,resp) grafico=ggplot(data,aes(y=resp,x=fator1))+ theme+ ylab(ylab)+ xlab(xlab) if(point=="mean_sd"){grafico=grafico+ stat_summary(aes(group=fator2),fun = mean,size=linesize, geom = "errorbar",na.rm=TRUE, fun.max = function(x) mean(x) + sd(x), fun.min = function(x) mean(x) - sd(x),width=width.bar)+ stat_summary(aes(shape=fator2),fun="mean", geom="point", size=pointsize, na.rm=TRUE)} if(point=="mean_se"){grafico=grafico+ stat_summary(aes(group=fator2),fun.data=mean_se, geom="errorbar", na.rm=TRUE,width=width.bar,size=linesize)+ stat_summary(aes(shape=fator2,group=fator2),fun="mean", geom="point",na.rm=TRUE, size=pointsize)} if(point=="mean"){grafico=grafico+ stat_summary(aes(shape=fator2,group=fator2),fun="mean", geom="point", na.rm=TRUE, size=pointsize)} if(point=="all"){grafico=grafico+ geom_point(aes(shape=fator2),size=pointsize,na.rm = TRUE)} if(is.na(ylim[1])==TRUE){grafico=grafico}else{grafico=grafico+ylim(ylim)} for(i in 1:length(levels(Fator2))){ y=resp[Fator2==levels(Fator2)[i]] x=fator1[Fator2==levels(Fator2)[i]] f2=fator2[Fator2==levels(Fator2)[i]] d1=data.frame(y,x,f2) adj=grau[i] numero=order(levels(Fator2))[levels(Fator2)==levels(Fator2)[i]] if(adj==0){mod="ns"} if(adj==1){mod=lm(y~x)} if(adj==2){mod=lm(y~x+I(x^2))} if(adj==3){mod=lm(y~x+I(x^2)+I(x^3))} if(adj==1 | adj==2 | adj==3){ modf1=lm(y~x); modf1ql=anova(modf1) modf2=lm(y~x+I(x^2)); modf2ql=anova(modf2) modf3=lm(y~x+I(x^2)+I(x^3)); modf3ql=anova(modf3) modf1q=aov(y~as.factor(x)) fadj1=anova(modf1,modf1q)[2,c(3,4,5,6)] fadj2=anova(modf2,modf1q)[2,c(3,4,5,6)] fadj3=anova(modf3,modf1q)[2,c(3,4,5,6)] if(is.na(DFres)==TRUE){DFres=anovaquali[4,1]} if(is.na(SSq)==TRUE){SSq=anovaquali[4,2]} df1=c(modf3ql[1,1],fadj1[1,1],DFres) df2=c(modf3ql[1:2,1],fadj2[1,1],DFres) df3=c(modf3ql[1:3,1],fadj3[1,1],DFres) sq1=c(modf3ql[1,2],fadj1[1,2],SSq) sq2=c(modf3ql[1:2,2],fadj2[1,2],SSq) sq3=c(modf3ql[1:3,2],fadj3[1,2],SSq) qm1=sq1/df1 qm2=sq2/df2 qm3=sq3/df3 if(adj==1){fa1=data.frame(cbind(df1,sq1,qm1)) fa1$f1=c(fa1$qm1[1:2]/fa1$qm1[3],NA) fa1$p=c(pf(fa1$f1[1:2],fa1$df1[1:2],fa1$df1[3],lower.tail = F),NA) rownames(fa1)=c("Linear","Deviation","Residual") fa=fa1} if(adj==2){fa2=data.frame(cbind(df2,sq2,qm2)) fa2$f2=c(fa2$qm2[1:3]/fa2$qm2[4],NA) fa2$p=c(pf(fa2$f2[1:3],fa2$df2[1:3],fa2$df2[4],lower.tail = F),NA) rownames(fa2)=c("Linear","Quadratic","Deviation","Residual") fa=fa2} if(adj==3){ fa3=data.frame(cbind(df3,sq3,qm3)) fa3$f3=c(fa3$qm3[1:4]/fa3$qm3[5],NA) fa3$p=c(pf(fa3$f3[1:4],fa3$df3[1:4],fa3$df3[5],lower.tail = F),NA) rownames(fa3)=c("Linear","Quadratic","Cubic","Deviation","Residual") fa=fa3} colnames(fa)=c("Df","SSq","MSQ","F","p-value") desvios[[i]]=as.matrix(fa) curvas[[i]]=summary(mod)$coefficients names(desvios)[i]=paste("Anova",levels(Fator2)[i]) names(curvas)[i]=levels(Fator2)[i] } fats=as.character(unique(Fator2)[i]) if(adj==1){grafico=grafico+geom_smooth(data = data[fator2==levels(Fator2)[i],],aes(color=unique(fator2),lty=unique(fator2)), method="lm", formula = y~x,na.rm=TRUE, se=se,size=linesize, show.legend=FALSE)} if(adj==2){grafico=grafico+geom_smooth(data = data[fator2==levels(Fator2)[i],],aes(color=unique(fator2),lty=unique(fator2)), method="lm", formula = y~x+I(x^2),na.rm=TRUE, se=se,size=linesize, show.legend=FALSE)} if(adj==3){grafico=grafico+geom_smooth(data = data[fator2==levels(Fator2)[i],],aes(color=unique(fator2),lty=unique(fator2)), method="lm", formula = y~x+I(x^2)+I(x^3),na.rm=TRUE, se=se,size=linesize, show.legend=FALSE)} m1=tapply(y,x,mean, na.rm=TRUE); x1=tapply(x,x,mean, na.rm=TRUE) if(adj==0){r2=0} if(adj==1){mod1=lm(m1~x1) r2=round(summary(mod1)$r.squared,2)} if(adj==2){mod1=lm(m1~x1+I(x1^2)) r2=round(summary(mod1)$r.squared,2)} if(adj==3){mod1=lm(m1~x1+I(x1^2)+I(x1^3)) r2=round(summary(mod1)$r.squared,2)} if(adj==0){text=sprintf("ns")} if(adj==1){ if(is.na(n)==FALSE){coef1=round(coef(mod)[1],n)}else{coef1=coef(mod)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod)[2],n)}else{coef2=coef(mod)[2]} text=sprintf("y == %0.3e %s %0.3e*x ~~~~~ italic(R^2) == %0.2f", coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), r2)} if(adj==2){ if(is.na(n)==FALSE){coef1=round(coef(mod)[1],n)}else{coef1=coef(mod)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod)[2],n)}else{coef2=coef(mod)[2]} if(is.na(n)==FALSE){coef3=round(coef(mod)[3],n)}else{coef3=coef(mod)[3]} text=sprintf("y == %0.3e %s %0.3e * x %s %0.3e * x^2 ~~~~~ italic(R^2) == %0.2f", coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), ifelse(coef3 >= 0, "+", "-"), abs(coef3), r2)} if(adj==3){ if(is.na(n)==FALSE){coef1=round(coef(mod)[1],n)}else{coef1=coef(mod)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod)[2],n)}else{coef2=coef(mod)[2]} if(is.na(n)==FALSE){coef3=round(coef(mod)[3],n)}else{coef3=coef(mod)[3]} if(is.na(n)==FALSE){coef4=round(coef(mod)[4],n)}else{coef4=coef(mod)[4]} text=sprintf("y == %0.3e %s %0.3e * x %s %0.3e * x^2 %s %0.3e * x^3 ~~~~~~ italic(R^2) == %0.2f", coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), ifelse(coef3 >= 0, "+", "-"), abs(coef3), ifelse(coef4 >= 0, "+", "-"), abs(coef4), r2)} texto[[i]]=text } if(point=="mean_sd"){grafico=grafico+ stat_summary(aes(group=fator2),fun = mean,size=0.7, geom = "errorbar",na.rm=TRUE, fun.max = function(x) mean(x) + sd(x), fun.min = function(x) mean(x) - sd(x),width=width.bar)+ stat_summary(aes(shape=fator2),fun="mean", geom="point", size=pointsize, na.rm=TRUE)} if(point=="mean_se"){grafico=grafico+ stat_summary(aes(group=fator2),fun.data=mean_se, geom="errorbar", na.rm=TRUE,width=width.bar,size=0.7)+ stat_summary(aes(shape=fator2,group=fator2),fun="mean", geom="point",na.rm=TRUE, size=pointsize)} if(point=="mean"){grafico=grafico+ stat_summary(aes(shape=fator2,group=fator2),fun="mean", geom="point", na.rm=TRUE, size=pointsize)} if(point=="all"){grafico=grafico+ geom_point(aes(shape=fator2),size=pointsize,na.rm = TRUE)} cat("\n----------------------------------------------------\n") cat("Regression Models") cat("\n----------------------------------------------------\n") print(curvas) cat("\n----------------------------------------------------\n") cat("Anova") cat("\n----------------------------------------------------\n") print(desvios,na.print=" ") grafico=grafico+ scale_linetype_manual(name=legend.title,values = color,drop=FALSE, label=parse(text=paste( separate[1], levels(Fator2), separate[2],"~",unlist(texto))))+ scale_shape_discrete(label=parse(text=paste(separate[1], levels(Fator2), separate[2],"~",unlist(texto)))) grafico=grafico+theme(text = element_text(size=textsize,color="black", family = family), axis.text = element_text(size=textsize,color="black", family = family), axis.title = element_text(size=textsize,color="black", family = family), legend.position = posi, legend.text=element_text(size=textsize), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ labs(color=legend.title, shape=legend.title, lty=legend.title)+ scale_color_grey(name=legend.title, start = 0.12, end = 0.1, label=parse(text=paste("(\"",levels(Fator2),"\")~",unlist(texto)))) print(grafico) (grafico=as.list(grafico)) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/polynomial2_function.R
#' Analysis: Linear regression graph in double factorial with color graph #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @description Linear regression analysis for significant interaction of an experiment with two factors, one quantitative and one qualitative #' @param fator1 Numeric or complex vector with factor 1 levels #' @param resp Numerical vector containing the response of the experiment. #' @param fator2 Numeric or complex vector with factor 2 levels #' @param color Graph color (\emph{default} is NA) #' @param grau Degree of the polynomial (1,2 or 3) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param se Adds confidence interval (\emph{default} is FALSE) #' @param legend.title Title legend #' @param textsize Font size (\emph{default} is 12) #' @param family Font family (\emph{default} is sans) #' @param point Defines whether to plot all points ("all"), mean ("mean"), mean with standard deviation ("mean_sd") or mean with standard error (\emph{default} - "mean_se"). #' @param ylim y-axis scale #' @param posi Legend position #' @param width.bar width of the error bars of a regression graph. #' @param pointsize Point size (\emph{default} is 4) #' @param linesize line size (Trendline and Error Bar) #' @param separate Separation between treatment and equation (\emph{default} is c("(\"","\")")) #' @param n Number of decimal places for regression equations #' @param SSq Sum of squares of the residue #' @param DFres Residue freedom degrees #' @keywords regression #' @keywords Experimental #' @seealso \link{polynomial}, \link{polynomial2} #' @return Returns two or more linear, quadratic or cubic regression analyzes. #' @export #' @examples #' dose=rep(c(0,0,0,2,2,2,4,4,4,6,6,6),3) #' resp=c(8,7,5,23,24,25,30,34,36,80,90,80, #' 12,14,15,23,24,25,50,54,56,80,90,40, #' 12,14,15,3,4,5,50,54,56,80,90,40) #' trat=rep(c("A","B","C"),e=12) #' polynomial2_color(dose, resp, trat, grau=c(1,2,3)) polynomial2_color=function(fator1, resp, fator2, color=NA, grau=NA, ylab="Response", xlab="independent", theme=theme_classic(), se=FALSE, point="mean_se", legend.title="Tratamentos", posi="top", textsize=12, ylim=NA, family="sans", width.bar=NA, pointsize=5, linesize=0.8, separate=c("(\"","\")"), n=NA, DFres=NA, SSq=NA){ if(is.na(width.bar)==TRUE){width.bar=0.05*mean(fator1)} requireNamespace("ggplot2") anovaquali=anova(aov(resp~as.factor(fator1)*fator2)) Fator2=fator2=factor(fator2,unique(fator2)) if(is.na(color)[1]==TRUE){color=1:length(levels(Fator2))} if(is.na(grau)[1]==TRUE){grau=rep(1,length(levels(Fator2)))} curvas=c() texto=c() desvios=c() data=data.frame(fator1,fator2,resp) grafico=ggplot(data,aes(y=resp,x=fator1))+ theme+ ylab(ylab)+ xlab(xlab) if(point=="all"){grafico=grafico+ geom_point(aes(color=fator2),size=pointsize)} if(point=="mean_sd"){grafico=grafico+ stat_summary(aes(color=fator2),fun = mean,size=linesize, geom = "errorbar", fun.max = function(x) mean(x) + sd(x), fun.min = function(x) mean(x) - sd(x), width=width.bar, na.rm = TRUE)+ stat_summary(aes(color=fator2),fun = "mean", geom="point", size=pointsize,na.rm = TRUE)} if(point=="mean_se"){grafico=grafico+ stat_summary(aes(color=fator2),fun.data=mean_se, geom="errorbar",size=linesize, width=width.bar,na.rm = TRUE)+ stat_summary(aes(color=fator2),fun="mean", geom="point", #shape=21,fill="gray80", size=pointsize,na.rm = TRUE)} if(point=="mean"){grafico=grafico+ stat_summary(aes(color=fator2),fun="mean", #shape=21, size=pointsize, geom="point",na.rm = TRUE)} if(is.na(ylim[1])==TRUE){grafico=grafico}else{grafico=grafico+ylim(ylim)} for(i in 1:length(levels(Fator2))){ y=resp[Fator2==levels(Fator2)[i]] x=fator1[Fator2==levels(Fator2)[i]] f2=fator2[Fator2==levels(Fator2)[i]] d1=data.frame(y,x,f2) adj=grau[i] numero=order(levels(Fator2))[levels(Fator2)==levels(Fator2)[i]] if(adj==0){mod="ns"} if(adj==1){mod=lm(y~x)} if(adj==2){mod=lm(y~x+I(x^2))} if(adj==3){mod=lm(y~x+I(x^2)+I(x^3))} if(adj==1 | adj==2 | adj==3){ modf1=lm(y~x); modf1ql=anova(modf1) modf2=lm(y~x+I(x^2)); modf2ql=anova(modf2) modf3=lm(y~x+I(x^2)+I(x^3)); modf3ql=anova(modf3) modf1q=aov(y~as.factor(x)) fadj1=anova(modf1,modf1q)[2,c(3,4,5,6)] fadj2=anova(modf2,modf1q)[2,c(3,4,5,6)] fadj3=anova(modf3,modf1q)[2,c(3,4,5,6)] if(is.na(DFres)==TRUE){DFres=anovaquali[4,1]} if(is.na(SSq)==TRUE){SSq=anovaquali[4,2]} df1=c(modf3ql[1,1],fadj1[1,1],DFres) df2=c(modf3ql[1:2,1],fadj2[1,1],DFres) df3=c(modf3ql[1:3,1],fadj3[1,1],DFres) sq1=c(modf3ql[1,2],fadj1[1,2],SSq) sq2=c(modf3ql[1:2,2],fadj2[1,2],SSq) sq3=c(modf3ql[1:3,2],fadj3[1,2],SSq) qm1=sq1/df1 qm2=sq2/df2 qm3=sq3/df3 if(adj==1){fa1=data.frame(cbind(df1,sq1,qm1)) fa1$f1=c(fa1$qm1[1:2]/fa1$qm1[3],NA) fa1$p=c(pf(fa1$f1[1:2],fa1$df1[1:2],fa1$df1[3],lower.tail = F),NA) rownames(fa1)=c("Linear","Deviation","Residual") fa=fa1} if(adj==2){fa2=data.frame(cbind(df2,sq2,qm2)) fa2$f2=c(fa2$qm2[1:3]/fa2$qm2[4],NA) fa2$p=c(pf(fa2$f2[1:3],fa2$df2[1:3],fa2$df2[4],lower.tail = F),NA) rownames(fa2)=c("Linear","Quadratic","Deviation","Residual") fa=fa2} if(adj==3){ fa3=data.frame(cbind(df3,sq3,qm3)) fa3$f3=c(fa3$qm3[1:4]/fa3$qm3[5],NA) fa3$p=c(pf(fa3$f3[1:4],fa3$df3[1:4],fa3$df3[5],lower.tail = F),NA) rownames(fa3)=c("Linear","Quadratic","Cubic","Deviation","Residual") fa=fa3} colnames(fa)=c("Df","SSq","MSQ","F","p-value") desvios[[i]]=as.matrix(fa) curvas[[i]]=summary(mod)$coefficients names(desvios)[i]=paste("Anova",levels(Fator2)[i]) names(curvas)[i]=levels(Fator2)[i] } fats=as.character(unique(Fator2)[i]) if(adj==1){grafico=grafico+geom_smooth(data = data[fator2==levels(Fator2)[i],],aes(color=as.character(unique(fator2))), method="lm", formula = y~x,size=linesize, se=se, fill="gray70")} if(adj==2){grafico=grafico+geom_smooth(data = data[fator2==levels(Fator2)[i],],aes(color=unique(fator2)), method="lm", formula = y~x+I(x^2), size=linesize,se=se, fill="gray70")} if(adj==3){grafico=grafico+geom_smooth(data = data[fator2==levels(Fator2)[i],],aes(color=unique(fator2)), method="lm", formula = y~x+I(x^2)+I(x^3), size=linesize,se=se, fill="gray70")} m1=tapply(y,x,mean, na.rm=TRUE); x1=tapply(x,x,mean, na.rm=TRUE) if(adj==0){r2=0} if(adj==1){mod1=lm(m1~x1) r2=round(summary(mod1)$r.squared,2)} if(adj==2){mod1=lm(m1~x1+I(x1^2)) r2=round(summary(mod1)$r.squared,2)} if(adj==3){mod1=lm(m1~x1+I(x1^2)+I(x1^3)) r2=round(summary(mod1)$r.squared,2)} if(adj==0){text=sprintf("ns")} if(adj==1){ if(is.na(n)==FALSE){coef1=round(coef(mod)[1],n)}else{coef1=coef(mod)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod)[2],n)}else{coef2=coef(mod)[2]} text=sprintf("y == %0.3e %s %0.3e*x ~~~~~ italic(R^2) == %0.2f", coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), r2)} if(adj==2){ if(is.na(n)==FALSE){coef1=round(coef(mod)[1],n)}else{coef1=coef(mod)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod)[2],n)}else{coef2=coef(mod)[2]} if(is.na(n)==FALSE){coef3=round(coef(mod)[3],n)}else{coef3=coef(mod)[3]} text=sprintf("y == %0.3e %s %0.3e * x %s %0.3e * x^2 ~~~~~ italic(R^2) == %0.2f", coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), ifelse(coef3 >= 0, "+", "-"), abs(coef3), r2)} if(adj==3){ if(is.na(n)==FALSE){coef1=round(coef(mod)[1],n)}else{coef1=coef(mod)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod)[2],n)}else{coef2=coef(mod)[2]} if(is.na(n)==FALSE){coef3=round(coef(mod)[3],n)}else{coef3=coef(mod)[3]} if(is.na(n)==FALSE){coef4=round(coef(mod)[4],n)}else{coef4=coef(mod)[4]} text=sprintf("y == %0.3e %s %0.3e * x %s %0.3e * x^2 %s %0.3e * x^3 ~~~~~~ italic(R^2) == %0.2f", coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), ifelse(coef3 >= 0, "+", "-"), abs(coef3), ifelse(coef4 >= 0, "+", "-"), abs(coef4), r2)} texto[[i]]=text } if(point=="all"){grafico=grafico+ geom_point(aes(color=fator2),size=pointsize)} if(point=="mean_sd"){grafico=grafico+ stat_summary(aes(color=fator2),fun = mean,size=0.7, geom = "errorbar", fun.max = function(x) mean(x) + sd(x), fun.min = function(x) mean(x) - sd(x), width=width.bar, na.rm = TRUE)+ stat_summary(aes(color=fator2),fun = "mean", geom="point", # shape=21,fill="gray80", size=pointsize,na.rm = TRUE)} if(point=="mean_se"){grafico=grafico+ stat_summary(aes(color=fator2),fun.data=mean_se, geom="errorbar",size=0.7, width=width.bar,na.rm = TRUE)+ stat_summary(aes(color=fator2),fun="mean", geom="point", #shape=21,fill="gray80", size=pointsize,na.rm = TRUE)} if(point=="mean"){grafico=grafico+ stat_summary(aes(color=fator2),fun="mean", #shape=21, size=pointsize, geom="point",na.rm = TRUE)} cat("\n----------------------------------------------------\n") cat("Regression Models") cat("\n----------------------------------------------------\n") print(curvas) cat("\n----------------------------------------------------\n") cat("Anova") cat("\n----------------------------------------------------\n") print(desvios,na.print=" ") grafico=grafico+scale_colour_discrete(label=parse(text=paste( separate[1], levels(Fator2), separate[2],"~",unlist(texto),sep="")))+ theme(text = element_text(size=textsize,color="black", family = family), axis.text = element_text(size=textsize,color="black", family = family), axis.title = element_text(size=textsize,color="black", family = family), legend.position = posi, legend.text=element_text(size=textsize), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ labs(color=legend.title, shape=legend.title, lty=legend.title) print(grafico) (grafico=as.list(grafico)) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/polynomial2color_function.R
#' Analysis: Linear regression graph #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @description Linear regression analysis of an experiment with a quantitative factor or isolated effect of a quantitative factor #' @param resp Numerical vector containing the response of the experiment. #' @param trat Numerical vector with treatments (Declare as numeric) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param xname.poly X name in equation #' @param yname.poly Y name in equation #' @param grau Degree of the polynomial (1, 2 or 3) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param color Graph color (\emph{default} is gray80) #' @param posi Legend position #' @param textsize Font size #' @param family Font family #' @param pointsize Point size #' @param linesize line size (Trendline and Error Bar) #' @param ylim y-axis scale #' @param se Adds confidence interval (\emph{default} is FALSE) #' @param width.bar width of the error bars of a regression graph. #' @param point Defines whether to plot mean ("mean"), all repetitions ("all"),mean with standard deviation ("mean_sd") or mean with standard error (\emph{default} - "mean_se"). #' @param n Number of decimal places for regression equations #' @param SSq Sum of squares of the residue #' @param DFres Residue freedom degrees #' @return Returns linear, quadratic or cubic regression analysis. #' @keywords Regression #' @keywords Experimental #' @seealso \link{polynomial2}, \link{polynomial2_color} #' @export #' @examples #' data("phao") #' with(phao, polynomial(dose,comp, grau = 2)) polynomial=function(trat, resp, ylab="Response", xlab="Independent", yname.poly="y", xname.poly="x", grau=NA, theme=theme_classic(), point="mean_sd", color="gray80", posi="top", textsize=12, se=FALSE, ylim=NA, family="sans", pointsize=4.5, linesize=0.8, width.bar=NA, n=NA, SSq=NA, DFres=NA) {requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.1*mean(trat)} if(is.na(grau)==TRUE){grau=1} # ================================ # vetores # ================================ dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean, na.rm=TRUE) mod=c() mod1=c() mod2=c() modm=c() mod1m=c() mod2m=c() text1=c() text2=c() text3=c() mods=c() mod1s=c() mod2s=c() fparcial1=c() fparcial2=c() fparcial3=c() media=tapply(resp, trat, mean, na.rm=TRUE) desvio=tapply(resp, trat, sd, na.rm=TRUE) erro=tapply(resp, trat, sd, na.rm=TRUE)/sqrt(table(trat)) dose=tapply(trat, trat, mean, na.rm=TRUE) moda=lm(resp~trat) mod1a=lm(resp~trat+I(trat^2)) mod2a=lm(resp~trat+I(trat^2)+I(trat^3)) mods=summary(moda)$coefficients mod1s=summary(mod1a)$coefficients mod2s=summary(mod2a)$coefficients modm=lm(media~dose) mod1m=lm(media~dose+I(dose^2)) mod2m=lm(media~dose+I(dose^2)+I(dose^3)) modf1=lm(resp~trat) modf2=lm(resp~trat+I(trat^2)) modf3=lm(resp~trat+I(trat^2)+I(trat^3)) modf1ql=anova(modf1) modf2ql=anova(modf2) modf3ql=anova(modf3) modf1q=aov(resp~as.factor(trat)) res=anova(modf1q) fadj1=anova(modf1,modf1q)[2,c(3,4,5,6)] fadj2=anova(modf2,modf1q)[2,c(3,4,5,6)] fadj3=anova(modf3,modf1q)[2,c(3,4,5,6)] if(is.na(DFres)==TRUE){DFres=res[2,1]} if(is.na(SSq)==TRUE){SSq=res[2,2]} df1=c(modf3ql[1,1],fadj1[1,1],DFres) df2=c(modf3ql[1:2,1],fadj2[1,1],DFres) df3=c(modf3ql[1:3,1],fadj3[1,1],DFres) sq1=c(modf3ql[1,2],fadj1[1,2],SSq) sq2=c(modf3ql[1:2,2],fadj2[1,2],SSq) sq3=c(modf3ql[1:3,2],fadj3[1,2],SSq) qm1=sq1/df1 qm2=sq2/df2 qm3=sq3/df3 if(grau=="1"){fa1=data.frame(cbind(df1,sq1,qm1)) fa1$f1=c(fa1$qm1[1:2]/fa1$qm1[3],NA) fa1$p=c(pf(fa1$f1[1:2],fa1$df1[1:2],fa1$df1[3],lower.tail = F),NA) colnames(fa1)=c("Df","SSq","MSQ","F","p-value");rownames(fa1)=c("Linear","Deviation","Residual")} if(grau=="2"){fa2=data.frame(cbind(df2,sq2,qm2)) fa2$f2=c(fa2$qm2[1:3]/fa2$qm2[4],NA) fa2$p=c(pf(fa2$f2[1:3],fa2$df2[1:3],fa2$df2[4],lower.tail = F),NA) colnames(fa2)=c("Df","SSq","MSQ","F","p-value");rownames(fa2)=c("Linear","Quadratic","Deviation","Residual")} if(grau=="3"){ fa3=data.frame(cbind(df3,sq3,qm3)) fa3$f3=c(fa3$qm3[1:4]/fa3$qm3[5],NA) fa3$p=c(pf(fa3$f3[1:4],fa3$df3[1:4],fa3$df3[5],lower.tail = F),NA) colnames(fa3)=c("Df","SSq","MSQ","F","p-value");rownames(fa3)=c("Linear","Quadratic","Cubic","Deviation","Residual")} if(grau=="1"){r2=round(summary(modm)$r.squared, 2)} if(grau=="2"){r2=round(summary(mod1m)$r.squared, 2)} if(grau=="3"){r2=round(summary(mod2m)$r.squared, 2)} if(grau=="1"){ if(is.na(n)==FALSE){coef1=round(coef(moda)[1],n)}else{coef1=coef(moda)[1]} if(is.na(n)==FALSE){coef2=round(coef(moda)[2],n)}else{coef2=coef(moda)[2]} s1=s <- sprintf("%s == %e %s %e*%s ~~~~~ italic(R^2) == %0.2f", yname.poly, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.poly, r2)} if(grau=="2"){ if(is.na(n)==FALSE){coef1=round(coef(mod1a)[1],n)}else{coef1=coef(mod1a)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod1a)[2],n)}else{coef2=coef(mod1a)[2]} if(is.na(n)==FALSE){coef3=round(coef(mod1a)[3],n)}else{coef3=coef(mod1a)[3]} s2=s <- sprintf("%s == %e %s %e * %s %s %e * %s^2 ~~~~~ italic(R^2) == %0.2f", yname.poly, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.poly, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.poly, r2)} if(grau=="3"){ if(is.na(n)==FALSE){coef1=round(coef(mod2a)[1],n)}else{coef1=coef(mod2a)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod2a)[2],n)}else{coef2=coef(mod2a)[2]} if(is.na(n)==FALSE){coef3=round(coef(mod2a)[3],n)}else{coef3=coef(mod2a)[3]} if(is.na(n)==FALSE){coef4=round(coef(mod2a)[4],n)}else{coef4=coef(mod2a)[4]} s3=s <- sprintf("%s == %e %s %e * %s %s %e * %s^2 %s %0.e * %s^3 ~~~~~ italic(R^2) == %0.2f", yname.poly, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.poly, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.poly, ifelse(coef4 >= 0, "+", "-"), abs(coef4), xname.poly, r2)} data1=data.frame(trat,resp) data1=data.frame(trat=dose,#as.numeric(as.character(names(media))), resp=media, desvio, erro) grafico=ggplot(data1,aes(x=trat,y=resp)) if(point=="all"){grafico=grafico+ geom_point(data=dados, aes(y=resp,x=trat),shape=21, fill=color,color="black")} if(point=="mean_sd"){grafico=grafico+ geom_errorbar(aes(ymin=resp-desvio,ymax=resp+desvio),width=width.bar,size=linesize)} if(point=="mean_se"){grafico=grafico+ geom_errorbar(aes(ymin=resp-erro,ymax=resp+erro),width=width.bar,size=linesize)} if(point=="mean"){grafico=grafico} grafico=grafico+geom_point(aes(fill=as.factor(rep(1,length(resp)))),na.rm=TRUE, size=pointsize,shape=21, color="black")+ theme+ylab(ylab)+xlab(xlab) if(is.na(ylim[1])==TRUE){grafico=grafico}else{grafico=grafico+ylim(ylim)} if(grau=="0"){grafico=grafico+geom_line(y=mean(resp),size=linesize,lty=2)} if(grau=="1"){grafico=grafico+geom_smooth(method = "lm",se=se, na.rm=TRUE, formula = y~x,size=linesize,color="black")} if(grau=="2"){grafico=grafico+geom_smooth(method = "lm",se=se, na.rm=TRUE, formula = y~x+I(x^2),size=linesize,color="black")} if(grau=="3"){grafico=grafico+geom_smooth(method = "lm",se=se, na.rm=TRUE, formula = y~x+I(x^2)+I(x^3),size=linesize,color="black")} if(grau=="0"){grafico=grafico+ scale_fill_manual(values=color,label=paste("y =",round(mean(resp),3)),name="")} if(grau=="1"){grafico=grafico+ scale_fill_manual(values=color,label=c(parse(text=s1)),name="")} if(grau=="2"){grafico=grafico+ scale_fill_manual(values=color,label=c(parse(text=s2)),name="")} if(grau=="3"){grafico=grafico+ scale_fill_manual(values=color,label=c(parse(text=s3)),name="")} if(color=="gray"){if(grau=="1"){grafico=grafico+ scale_fill_manual(values="black",label=c(parse(text=s1)),name="")} if(grau=="2"){grafico=grafico+ scale_fill_manual(values="black",label=c(parse(text=s2)),name="")} if(grau=="3"){grafico=grafico+ scale_fill_manual(values="black",label=c(parse(text=s3)),name="")} } grafico=grafico+ theme(text = element_text(size=textsize,color="black",family=family), axis.text = element_text(size=textsize,color="black",family=family), axis.title = element_text(size=textsize,color="black",family=family), legend.position = posi, legend.text=element_text(size=textsize), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0) # print(grafico) if(grau==1){ cat("\n----------------------------------------------------\n") cat("Regression Models") cat("\n----------------------------------------------------\n") print(mods) cat("\n----------------------------------------------------\n") cat("Deviations from regression") cat("\n----------------------------------------------------\n") print(as.matrix(fa1),na.print=" ") } if(grau==2){ cat("\n----------------------------------------------------\n") cat("Regression Models") cat("\n----------------------------------------------------\n") print(mod1s) cat("\n----------------------------------------------------\n") cat("Deviations from regression") cat("\n----------------------------------------------------\n") print(as.matrix(fa2),na.print=" ") } if(grau==3){ cat("\n----------------------------------------------------\n") cat("Regression Models") cat("\n----------------------------------------------------\n") print(mod2s) cat("\n----------------------------------------------------\n") cat("Deviations from regression") cat("\n----------------------------------------------------\n") print(as.matrix(fa3),na.print=" ") } (graficos=list(grafico)) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/polynomial_function.R
#' Dataset: Pomegranate data #' #' @description An experiment was conducted with the objective of studying different #' products to reduce the loss of mass in postharvest of pomegranate fruits. #' The experiment was conducted in a completely randomized design with four #' replications. Treatments are: T1: External Wax; T2: External + Internal Wax; #' T3: External Orange Oil; T4: Internal + External Orange Oil; T5: External #' sodium hypochlorite; T6: Internal + External sodium hypochlorite #' #' @docType data #' #' @usage data(pomegranate) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{trat}}{Categorical vector with treatments} #' \item{\code{WL}}{Numeric vector weights loss} #' \item{\code{SS}}{Numeric vector solid soluble} #' \item{\code{AT}}{Numeric vector titratable acidity} #' \item{\code{ratio}}{Numeric vector with ratio (SS/AT)} #' } #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather}, \link{phao}, \link{passiflora} #' #' @keywords datasets #' #' @examples #' data(pomegranate) "pomegranate"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/pomegranate.R
#' Dataset: Pig development and production #' #' @description An experiment whose objective was to study the effect of castration #' age on the development and production of pigs, evaluating the weight #' of the piglets. Four treatments were studied: A - castration at #' 56 days of age; B - castration at 7 days of age; C - castration at #' 36 days of age; D - whole (not castrated); E - castration at 21 days #' of age. The Latin square design was used in order to control the #' variation between litters (lines) and the variation in the initial #' weight of the piglets (columns), with the experimental portion #' consisting of a piglet. #' #' @docType data #' #' @usage data(porco) #' #' @keywords datasets #' @format data.frame containing data set #' \describe{ #' \item{\code{trat}}{Categorical vector with treatments} #' \item{\code{linhas}}{Categorical vector with lines} #' \item{\code{colunas}}{Categorical vector with columns} #' \item{\code{resp}}{Numeric vector} #' } #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather}, \link{phao}, \link{passiflora}, \link{aristolochia} #' @keywords datasets #' #' @examples #' data(porco) "porco"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/porco.R
#' Analysis: Polynomial splitting for double factorial in DIC and DBC #' @description Splitting in polynomials for double factorial in DIC and DBC. Note that f1 must always be qualitative and f2 must always be quantitative. This function is an easier way to visualize trends for dual factor schemes with a quantitative and a qualitative factor. #' @param factors Define f1 and f2 and/or block factors in list form. Please note that in the list it is necessary to write `f1`, `f2` and `block`. See example. #' @param response response variable #' @param dec Number of cells #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @return Returns the coefficients of the linear, quadratic and cubic models, the p-values of the t test for each coefficient (p.value.test) and the p-values for the linear, quadratic, cubic model splits and the regression deviations. #' @keywords Experimental #' @seealso \link{FAT2DIC}, \link{FAT2DBC} #' @export #' @examples #' library(AgroR) #' data(cloro) #' quant.fat2.desd(factors = list(f1=cloro$f1, #' f2=rep(c(1:4),e=5,2), block=cloro$bloco), #' response=cloro$resp) quant.fat2.desd=function(factors=list(f1,f2,block), response, dec=3){ anlinear=function(trat,resp,sq,df){ a=anova(lm(resp~trat)) b=anova(lm(resp~as.factor(trat))) alin=rbind(a[1,],b[1,],"resid"=c(df,sq,sq/df,NA,NA)) alin$`Sum Sq`[2]=alin$`Sum Sq`[2]-alin$`Sum Sq`[1] alin$Df[2]=alin$Df[2]-alin$Df[1] alin$`Mean Sq`=alin$`Sum Sq`/alin$Df alin$`F value`=c(alin$`Mean Sq`[1:2]/alin$`Mean Sq`[3],NA) alin$`Pr(>F)`=c(1-pf(alin$`F value`[1:2],alin$Df[1:2],alin$Df[3]),NA) rownames(alin)=c("Linear","Deviation","Residuals") alin} anquad=function(trat,resp,sq,df){ a=anova(lm(resp~trat+I(trat^2))) b=anova(lm(resp~as.factor(trat))) alin=rbind(a[1:2,],b[1,],"resid"=c(df,sq,sq/df,NA,NA)) alin$`Sum Sq`[3]=alin$`Sum Sq`[3]-sum(alin$`Sum Sq`[1:2]) alin$Df[3]=alin$Df[3]-2 alin$`Mean Sq`=alin$`Sum Sq`/alin$Df alin$`F value`=c(alin$`Mean Sq`[1:3]/alin$`Mean Sq`[4],NA) alin$`Pr(>F)`=c(1-pf(alin$`F value`[1:3],alin$Df[1:3],alin$Df[4]),NA) rownames(alin)=c("Linear","Quadratic","Deviation","Residuals") alin} ancubic=function(trat,resp,sq,df){ a=anova(lm(resp~trat+I(trat^2)+I(trat^3))) b=anova(lm(resp~as.factor(trat))) alin=rbind(a[1:3,],b[1,],"resid"=c(df,sq,sq/df,NA,NA)) alin$`Sum Sq`[4]=alin$`Sum Sq`[4]-sum(alin$`Sum Sq`[1:3]) alin$Df[4]=alin$Df[4]-3 alin$`Mean Sq`=alin$`Sum Sq`/alin$Df alin$`F value`=c(alin$`Mean Sq`[1:4]/alin$`Mean Sq`[5],NA) alin$`Pr(>F)`=c(1-pf(alin$`F value`[1:4],alin$Df[1:4],alin$Df[5]),NA) rownames(alin)=c("Linear","Quadratic","Cubic","Deviation","Residuals") alin} requireNamespace("crayon") if(length(factors)==2){ f1=factors$f1; f1=factor(f1,unique(f1)) f2=factors$f2; f2=factor(f2,unique(f2)) f1a=factors$f1 f2a=factors$f2 nv1 <- length(summary(f1)) nv2 <- length(summary(f2)) lf1 <- levels(f1) lf2 <- levels(f2) mod=aov(response~f1*f2) #================================================================== mod1=aov(response~f1/f2) l1<-vector('list',nv1) names(l1)<-names(summary(f1)) v<-numeric(0) for(j in 1:nv1) { for(i in 0:(nv2-2)) v<-cbind(v,i*nv1+j) l1[[j]]<-v v<-numeric(0)} des1.tab<-summary(mod1,split=list('f1:f2'=l1))[[1]][-c(1,2),] cat(green("==========================================================")) cat(green("\nAnalyzing the interaction\n")) cat(green("==========================================================\n")) print(des1.tab) cat(green("\n\n==========================================================\n")) cate=as.list(1:nv1) modelo=anova(mod) for(i in 1:nv1){ resp=response[f1==lf1[i]] trat=f2a[f1==lf1[i]] linear=lm(resp~trat) quadratico=lm(resp~trat+I(trat^2)) cubico=lm(resp~trat+I(trat^2)+I(trat^3)) plinear=data.frame(summary(linear)$coefficients)$Pr...t.. pquad=data.frame(summary(quadratico)$coefficients)$Pr...t.. pcubic=data.frame(summary(cubico)$coefficients)$Pr...t.. # plinear=ifelse(plinear<0.0001,"p<0.0001",round(plinear,4)) # pquad=ifelse(pquad<0.0001,"p<0.0001",round(pquad,4)) # pcubic=ifelse(pcubic<0.0001,"p<0.0001",round(pcubic,4)) a=anlinear(trat,resp,sq=modelo$`Sum Sq`[4],df=modelo$Df[4]) b=anquad(trat,resp,sq=modelo$`Sum Sq`[4],df=modelo$Df[4]) c=ancubic(trat,resp,sq=modelo$`Sum Sq`[4],df=modelo$Df[4]) cate[[i]]=t(data.frame(intercept=c(round(coef(linear)[1],dec), round(coef(quadratico)[1],dec), round(coef(cubico)[1],dec)), beta1=c(round(coef(linear)[2],dec), round(coef(quadratico)[2],dec), round(coef(cubico)[2],dec)), beta2=c(NA,round(coef(quadratico)[3],dec), round(coef(cubico)[3],dec)), beta3=c(NA, NA, round(coef(cubico)[4],dec)), "p.value.test"=c(NA,NA,NA), pb0=c(round(plinear[1],dec),round(pquad[1],dec),round(pcubic[1],dec)), pb1=c(round(plinear[2],dec),round(pquad[2],dec),round(pcubic[2],dec)), pb2=c(NA,round(pquad[3],dec),round(pcubic[3],dec)), pb3=c(NA,NA,round(pcubic[4],dec)), "p.value.mod"=c(NA,NA,NA), linear=c(round(a$`Pr(>F)`[1],dec),round(b$`Pr(>F)`[1],dec),round(c$`Pr(>F)`[1],dec)), quadratic=c(NA,round(b$`Pr(>F)`[2],dec),round(c$`Pr(>F)`[2],dec)), cubic=c(NA,NA,round(c$`Pr(>F)`[3],dec)), deviation=c(round(a$`Pr(>F)`[2],dec),round(b$`Pr(>F)`[3],dec),round(c$`Pr(>F)`[4],dec)))) colnames(cate[[i]])=c("Linear","Quadratic","Cubic") } names(cate)=lf1 print(cate,na.print = "") } if(length(factors)>2){ f1=factors$f1; f1=factor(f1,unique(f1)) f2=factors$f2; f2=factor(f2,unique(f2)) block=factors$block bloco=factors$block; bloco=factor(bloco,unique(bloco)) f1a=factors$f1 f2a=factors$f2 nv1 <- length(summary(f1)) nv2 <- length(summary(f2)) lf1 <- levels(f1) lf2 <- levels(f2) mod=aov(response~f1*f2+bloco) mod1=aov(response~f1/f2+bloco) l1<-vector('list',nv1) names(l1)<-names(summary(f1)) v<-numeric(0) for(j in 1:nv1) { for(i in 0:(nv2-2)) v<-cbind(v,i*nv1+j) l1[[j]]<-v v<-numeric(0)} des1.tab<-summary(mod1,split=list('f1:f2'=l1))[[1]][-c(1,2,3),] cat(green("==========================================================")) cat(green("\nDesdobramento\n")) cat(green("==========================================================\n")) print(des1.tab) cat(green("\n\n==========================================================\n")) cate=as.list(1:nv1) modelo=anova(mod) for(i in 1:nv1){ resp=response[f1==lf1[i]] trat=f2a[f1==lf1[i]] linear=lm(resp~trat) quadratico=lm(resp~trat+I(trat^2)) cubico=lm(resp~trat+I(trat^2)+I(trat^3)) plinear=data.frame(summary(linear)$coefficients)$Pr...t.. pquad=data.frame(summary(quadratico)$coefficients)$Pr...t.. pcubic=data.frame(summary(cubico)$coefficients)$Pr...t.. # plinear=ifelse(plinear<0.0001,"p<0.0001",round(plinear,4)) # pquad=ifelse(pquad<0.0001,"p<0.0001",round(pquad,4)) # pcubic=ifelse(pcubic<0.0001,"p<0.0001",round(pcubic,4)) a=anlinear(trat,resp,sq=modelo$`Sum Sq`[5],df=modelo$Df[5]) b=anquad(trat,resp,sq=modelo$`Sum Sq`[5],df=modelo$Df[5]) c=ancubic(trat,resp,sq=modelo$`Sum Sq`[5],df=modelo$Df[5]) cate[[i]]=t(data.frame(intercept=c(round(coef(linear)[1],dec), round(coef(quadratico)[1],dec), round(coef(cubico)[1],dec)), beta1=c(round(coef(linear)[2],dec), round(coef(quadratico)[2],dec), round(coef(cubico)[2],dec)), beta2=c(NA,round(coef(quadratico)[3],dec), round(coef(cubico)[3],dec)), beta3=c(NA, NA, round(coef(cubico)[4],dec)), "p.value.test"=c(NA,NA,NA), pb0=c(round(plinear[1],dec),round(pquad[1],dec),round(pcubic[1],dec)), pb1=c(round(plinear[2],dec),round(pquad[2],dec),round(pcubic[2],dec)), pb2=c(NA,round(pquad[3],dec),round(pcubic[3],dec)), pb3=c(NA,NA,round(pcubic[4],dec)), "p.value.mod"=c(NA,NA,NA), linear=c(round(a$`Pr(>F)`[1],dec),round(b$`Pr(>F)`[1],dec),round(c$`Pr(>F)`[1],dec)), quadratic=c(NA,round(b$`Pr(>F)`[2],dec),round(c$`Pr(>F)`[2],dec)), cubic=c(NA,NA,round(c$`Pr(>F)`[3],dec)), deviation=c(round(a$`Pr(>F)`[2],dec),round(b$`Pr(>F)`[3],dec),round(c$`Pr(>F)`[4],dec)))) colnames(cate[[i]])=c("Linear","Quadratic","Cubic")} names(cate)=lf1 print(cate,na.print = "")} }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/quantfat2desd_function.R
#' Graph: Circular column chart #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @description Circular column chart of an experiment with a factor of interest or isolated effect of a factor #' @param model DIC, DBC or DQL object #' @param ylim y-axis limit #' @param transf If the data has been transformed (\emph{default} is FALSE) #' @param labelsize Font size of the labels #' @seealso \link{barplot_positive}, \link{sk_graph}, \link{plot_TH}, \link{corgraph}, \link{spider_graph}, \link{line_plot} #' @return Returns pie chart with averages and letters from the Scott-Knott cluster test #' @export #' @examples #' data("laranja") #' a=with(laranja, DBC(trat,bloco,resp, mcomp = "sk")) #' radargraph(a) radargraph=function(model, ylim=NA, labelsize=4, transf=FALSE){ a=model requireNamespace("ggplot2") data=a[[1]]$data size=a[[1]]$theme$axis.text$size ylab=a[[1]]$labels$y xlab=a[[1]]$labels$x trats=data$trats media=data$media # if(transf==FALSE){ # data$resp=data$resp # resp=data$resp} # if(transf==TRUE){ # data$resp=data$respo # resp=data$respo} letra=data$letra groups=data$groups data$id=id=c(1:length(data$media)) label_data = data number_of_bar = nrow(data) angle = 90 - 360 * (label_data$id-0.5)/number_of_bar label_data$hjust=hjust=ifelse( angle < -90, 1, 0) label_data$angle=ifelse(angle < -90, angle+180, angle) limite=label_data$limite graph=ggplot(data, aes(x=trats, y=media))+ geom_bar(aes(fill=groups), stat="identity", color="black",show.legend = FALSE) if(is.na(ylim)==TRUE){graph=graph+ylim(-min(media),1.2*max(media))} if(is.na(ylim)==FALSE){graph=graph+ylim(ylim)} graph=graph+theme_minimal() + theme(axis.text = element_blank(), axis.title = element_blank(), panel.grid = element_blank(), plot.margin = unit(rep(-1,4), "cm")) + coord_polar(start = 0) + geom_text(data=label_data, aes(x=id, y=limite, label=paste(data$trats,"\n",letra), hjust=hjust), color="black", fontface="bold", alpha=0.6, size=4, angle= label_data$angle, inherit.aes = FALSE ) print(graph) grafico=list(graph)[[1]] }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/radargraph_function.R
#' Graph: Point graph for one factor model 2 #' #' @description This is a function of the point graph for one factor #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param model DIC, DBC or DQL object #' @param theme ggplot2 theme #' @param horiz Horizontal Column (\emph{default} is TRUE) #' @param pointsize Point size #' @param pointshape Format point (default is 16) #' @param vjust vertical adjusted #' @export #' @return Returns a point chart for one factor #' @seealso \link{radargraph}, \link{barplot_positive}, \link{plot_TH}, \link{corgraph}, \link{spider_graph}, \link{line_plot} #' @examples #' data("laranja") #' a=with(laranja, DBC(trat, bloco, resp, #' mcomp = "sk",angle=45, #' ylab = "Number of fruits/plants")) #' seg_graph2(a,horiz = FALSE) seg_graph2=function(model, theme=theme_gray(), pointsize=4, pointshape=16, horiz=TRUE, vjust=-0.6){ requireNamespace("ggplot2") data=model[[1]]$data media=data$media desvio=data$desvio trats=data$trats limite=data$limite letra=data$letra groups=data$groups sup=model[[1]]$plot$sup if(horiz==TRUE){ graph=ggplot(data,aes(y=trats, x=media))+theme+ geom_errorbar(aes(xmin=media-desvio, xmax=media+desvio),width=0,size=0.8)+ geom_point(size=pointsize,shape=16, fill="black", color="black")+ geom_text(aes(x=media, y=trats, label = letra),vjust=vjust,family=model[[1]]$plot$family)+ labs(y=model[[1]]$labels$x, x=model[[1]]$labels$y)+ theme(axis.text = element_text(size=12,color="black"), strip.text = element_text(size=12), legend.position = "none")+ scale_y_discrete(limits=trats)+ xlim(layer_scales(model[[1]])$y$range$range)} if(horiz==FALSE){ graph=ggplot(data,aes(x=trats, y=media))+theme+ geom_errorbar(aes(ymin=media-desvio, ymax=media+desvio),width=0,size=0.8)+ geom_point(size=pointsize,shape=16, fill="black", color="black")+ geom_text(aes(y=media, x=trats, label = letra),vjust=vjust,angle=90,family=model[[1]]$plot$family)+ labs(x=model[[1]]$labels$x, y=model[[1]]$labels$y)+ theme(axis.text = element_text(size=12,color="black"), strip.text = element_text(size=12), legend.position = "none")+ scale_x_discrete(limits=trats)+ ylim(layer_scales(model[[1]])$y$range$range)} graph }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/seggraph2_function.R
#' Graph: Point graph for one factor #' #' @description This is a function of the point graph for one factor #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param model DIC, DBC or DQL object #' @param fill fill bars #' @param horiz Horizontal Column (\emph{default} is TRUE) #' @param pointsize Point size #' @export #' @return Returns a point chart for one factor #' @seealso \link{radargraph}, \link{barplot_positive}, \link{plot_TH}, \link{corgraph}, \link{spider_graph}, \link{line_plot} #' @examples #' data("laranja") #' a=with(laranja, DBC(trat, bloco, resp, #' mcomp = "sk",angle=45,sup=10, #' ylab = "Number of fruits/plants")) #' seg_graph(a,horiz = FALSE) seg_graph=function(model, fill="lightblue", horiz=TRUE, pointsize=4.5){ requireNamespace("ggplot2") data=model[[1]]$data media=data$media desvio=data$desvio trats=data$trats limite=data$limite letra=data$letra groups=data$groups sup=model[[1]]$plot$sup if(horiz==TRUE){ graph=ggplot(data,aes(y=trats, x=media))+ model[[1]]$theme+ geom_errorbar(aes(xmin=media-desvio, xmax=media+desvio),width=0.2,size=0.8)+ geom_point(size=pointsize,shape=21, fill=fill, color="black")+ geom_text(aes(x=media+desvio+sup, y=trats, label = letra),hjust=0,family=model[[1]]$plot$family)+ labs(y=model[[1]]$labels$x, x=model[[1]]$labels$y)+ theme(axis.text = element_text(size=12,color="black"), strip.text = element_text(size=12), legend.position = "none")+ scale_y_discrete(limits=trats)+ xlim(layer_scales(model[[1]])$y$range$range)} if(horiz==FALSE){ graph=ggplot(data,aes(x=trats, y=media))+ model[[1]]$theme+ geom_errorbar(aes(ymin=media-desvio, ymax=media+desvio),width=0.2,size=0.8)+ geom_point(fill=fill,size=pointsize,shape=21,color="black")+ geom_text(aes(y=media+desvio+sup, x=trats, label = letra),vjust=0,family=model[[1]]$plot$family)+ labs(x=model[[1]]$labels$x, y=model[[1]]$labels$y)+ theme(axis.text = element_text(size=12,color="black"), strip.text = element_text(size=12), legend.position = "none")+ scale_x_discrete(limits=trats)+ ylim(layer_scales(model[[1]])$y$range$range)} graph }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/seggraph_function.R
#' Dataset: Sensorial data #' #' @description Set of data from a sensory analysis with six participants in which different combinations (blend) of the grape cultivar bordo and niagara were evaluated. Color (CR), aroma (AR), flavor (SB), body (CP) and global (GB) were evaluated. The data.frame presents the averages of the evaluators. #' @docType data #' #' @usage data(sensorial) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{Blend}}{Categorical vector with treatment} #' \item{\code{variable}}{Categorical vector with variables} #' \item{\code{resp}}{Numeric vector} #' } #' #' @keywords datasets #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather}, \link{phao}, \link{passiflora}, \link{aristolochia} #' @examples #' data(sensorial) "sensorial"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/sensorial.R
#' Dataset: Simulated data dict #' #' @docType data #' #' @description Simulated data from a completely randomized experiment with multiple assessments over time #' @usage data(simulate1) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{tempo}}{Categorical vector with time} #' \item{\code{trat}}{Categorical vector with treatment} #' \item{\code{resp}}{Categorical vector with response} #' } #' @keywords datasets #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{sensorial}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather}, \link{phao}, \link{passiflora}, \link{aristolochia} #' @examples #' data(simulate1) "simulate1"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/simulate1.R
#' Dataset: Simulated data dbct #' #' @docType data #' #' @description Simulated data from a latin square experiment with multiple assessments over time #' #' @usage data(simulate2) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{tempo}}{Categorical vector with time} #' \item{\code{trat}}{Categorical vector with treatment} #' \item{\code{bloco}}{Categorical vector with block} #' \item{\code{resp}}{Categorical vector with response} #' } #' @keywords datasets #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate3}, \link{tomate}, \link{weather}, \link{phao}, \link{passiflora}, \link{aristolochia} #' @examples #' data(simulate2) "simulate2"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/simulate2.R
#' Dataset: Simulated data dqlt #' #' @docType data #' #' @usage data(simulate3) #' #' @description Simulated data from a completely randomized experiment with multiple assessments over time #' #' @format data.frame containing data set #' \describe{ #' \item{\code{tempo}}{Categorical vector with time} #' \item{\code{trat}}{Categorical vector with treatment} #' \item{\code{linhas}}{Categorical vector with line} #' \item{\code{colunas}}{Categorical vector with column} #' \item{\code{resp}}{Categorical vector with response} #' } #' @keywords datasets #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{tomate}, \link{weather}, \link{phao}, \link{passiflora}, \link{aristolochia} #' @examples #' data(simulate3) "simulate3"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/simulate3.R
#' Graph: Scott-Knott graphics #' #' @description This is a function of the bar graph for the Scott-Knott test #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param model DIC, DBC or DQL object #' @param horiz Horizontal Column (\emph{default} is TRUE) #' @export #' @return Returns a bar chart with columns separated by color according to the Scott-Knott test #' @seealso \link{radargraph}, \link{barplot_positive}, \link{plot_TH}, \link{corgraph}, \link{spider_graph}, \link{line_plot} #' @examples #' data("laranja") #' a=with(laranja, DBC(trat, bloco, resp, #' mcomp = "sk",angle=45, #' ylab = "Number of fruits/plants")) #' sk_graph(a,horiz = FALSE) #' library(ggplot2) #' sk_graph(a,horiz = TRUE)+scale_fill_grey(start=1,end=0.5) sk_graph=function(model, horiz=TRUE){ requireNamespace("ggplot2") data=model[[1]]$data family=model[[1]]$plot$family media=data$media desvio=data$desvio trats=data$trats limite=data$limite letra=data$letra groups=data$groups sup=model[[1]]$plot$sup ploterror=model[[1]]$plot$errorbar # if(transf==FALSE){data=data[,c(5,1,2)]} # if(transf==TRUE){data=data[,c(6,3,2)]} if(horiz==TRUE){ graph=ggplot(data,aes(y=as.vector(trats), x=as.vector(media)))+ model[[1]]$theme+ geom_col(aes(fill=as.vector(groups)), size=0.3, color="black") if(ploterror==TRUE){graph=graph+geom_errorbar(aes(xmax=media+desvio,xmin=media-desvio), width=model[[1]]$layers[3][[1]]$geom_params$width)+ geom_label(aes(x=as.vector(media)+sup+desvio, y=as.vector(trats), label = letra),family=family, fill="lightyellow",hjust=0)} if(ploterror==FALSE){graph=graph+geom_label(aes(x=as.vector(media)+sup, y=as.vector(trats), label = letra),family=family, fill="lightyellow",hjust=0)} graph=graph+ labs(y=model[[1]]$labels$x, x=model[[1]]$labels$y)+ theme(axis.text = element_text(size=12,color="black"), strip.text = element_text(size=12), legend.position = "none")+ scale_y_discrete(limits=data$trats)+ xlim(layer_scales(model[[1]])$y$range$range*1.1)} if(horiz==FALSE){ graph=ggplot(data,aes(x=as.vector(trats), y=as.vector(media)))+ model[[1]]$theme+ geom_col(aes(fill=as.vector(groups)),size=0.3, color="black") if(ploterror==TRUE){graph=graph+geom_errorbar(aes(ymax=media+desvio,ymin=media-desvio), width=model[[1]]$layers[3][[1]]$geom_params$width)+ geom_label(aes(y=as.vector(media)+sup+desvio, x=as.vector(trats), label = letra),family=family, fill="lightyellow")} if(ploterror==FALSE){graph=graph+geom_label(aes(y=as.vector(media)+sup, x=as.vector(trats), label = letra),family=family, fill="lightyellow",hjust=0)} graph=graph+ labs(x=model[[1]]$labels$x, y=model[[1]]$labels$y)+ theme(axis.text = element_text(size=12,color="black"), strip.text = element_text(size=12), legend.position = "none")+ scale_x_discrete(limits=data$trats)+ ylim(layer_scales(model[[1]])$y$range$range)} graph }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/sk_graph_function.R
#' Dataset: Soybean #' #' An experiment was carried out to evaluate the grain yield (kg ha-1) of ten different #' commercial soybean cultivars in the municipality of Londrina/Parana. The experiment was carried out in the design of #' randomized complete blocks with four replicates per treatment. #' @docType data #' #' @usage data("soybean") #' #' @format data.frame containing data set #' \describe{ #' \item{\code{cult}}{numeric vector with treatment} #' \item{\code{bloc}}{numeric vector with block} #' \item{\code{prod}}{Numeric vector with grain yield} #' } #' @keywords datasets #' @seealso \link{cloro}, \link{laranja}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{passiflora}, \link{phao}, \link{porco}, \link{pomegranate}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{weather} #' @examples #' data(soybean) "soybean" #'
/scratch/gouwar.j/cran-all/cranData/AgroR/R/soybean_dataset.R
#' Graph: Spider graph for sensorial analysis #' #' @description Spider chart or radar chart. Usually used for graphical representation of acceptability in sensory tests #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param resp Vector containing notes #' @param vari Vector containing the variables #' @param blend Vector containing treatments #' @param legend.title Caption title #' @param xlab x axis title #' @param ylab y axis title #' @param ymin Minimum value of y #' @seealso \link{radargraph}, \link{sk_graph}, \link{plot_TH}, \link{corgraph}, \link{barplot_positive}, \link{line_plot} #' @return Returns a spider or radar chart. This graph is commonly used in studies of sensory analysis. #' @export #' @examples #' library(AgroR) #' data(sensorial) #' with(sensorial, spider_graph(resp, variable, Blend)) spider_graph=function(resp, vari, blend, legend.title="", xlab="", ylab="", ymin=0){ requireNamespace("ggplot2") dados=data.frame(blend,vari,resp) dados$vari=factor(dados$vari,levels = unique(dados$vari)) dados$blend=factor(dados$blend,levels = unique(dados$blend)) grafico=ggplot(dados,aes(x=vari,y=resp))+ theme_bw()+ geom_point(aes(color=blend),size=4)+ scale_color_manual(values=1:6)+ylim(ymin,ceiling(max(resp))) for(i in 1:nlevels(as.factor(blend))){ grafico=grafico+ geom_point(data=dados[dados$blend==levels(as.factor(dados$blend))[i],], aes(x=vari,y=resp),color=i, size=4)+ geom_polygon(data=dados[dados$blend==levels(as.factor(dados$blend))[i],], aes(x=vari,y=resp,group=1), color=i, fill=i,alpha=0.05,size=1)} theta = "x"; start = 0; direction = 1 r <- if (theta == "x") "y" else "x" grafico=grafico+ coord_polar()+ ggproto("CordRadar", CoordPolar, theta = theta, r = r, start = start, direction = sign(direction), is_linear = function(coord) TRUE)+ theme(axis.text = element_text(size=12,color="black"), panel.border= element_rect(color = "white"), panel.grid = element_line(color="gray70"))+ labs(y=ylab,color=legend.title,x=xlab) graficos=as.list(grafico) print(grafico)}
/scratch/gouwar.j/cran-all/cranData/AgroR/R/spider_graph_function.R
#' Analysis: DBC experiments in strip-plot #' @description Analysis of an experiment conducted in a block randomized design in a strit-plot scheme using fixed effects analysis of variance. #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param f1 Numeric or complex vector with plot levels #' @param f2 Numeric or complex vector with subplot levels #' @param block Numeric or complex vector with blocks #' @param response Numeric vector with responses #' @param transf Applies data transformation (default is 1; for log consider 0) #' @param constant Add a constant for transformation (enter value) #' @param norm Error normality test (\emph{default} is Shapiro-Wilk) #' @param alpha.f Level of significance of the F test (\emph{default} is 0.05) #' @param textsize Font size (\emph{default} is 12) #' @param labelsize Label size (\emph{default} is 4) #' @import ggplot2 #' @importFrom crayon green #' @importFrom crayon bold #' @importFrom crayon italic #' @importFrom crayon red #' @importFrom crayon blue #' @import stats #' @keywords DBC #' @export #' @references #' #' Principles and procedures of statistics a biometrical approach Steel, Torry and Dickey. Third Edition 1997 #' #' Multiple comparisons theory and methods. Departament of statistics the Ohio State University. USA, 1996. Jason C. Hsu. Chapman Hall/CRC. #' #' Practical Nonparametrics Statistics. W.J. Conover, 1999 #' #' Ramalho M.A.P., Ferreira D.F., Oliveira A.C. 2000. Experimentacao em Genetica e Melhoramento de Plantas. Editora UFLA. #' #' Scott R.J., Knott M. 1974. A cluster analysis method for grouping mans in the analysis of variance. Biometrics, 30, 507-512. #' @return The table of analysis of variance, the test of normality of errors (Shapiro-Wilk, Lilliefors, Anderson-Darling, Cramer-von Mises, Pearson and Shapiro-Francia), the test of homogeneity of variances (Bartlett). The function also returns a standardized residual plot. #' @examples #' #' #=================================== #' # Example tomate #' #=================================== #' # Obs. Consider that the "tomato" experiment is a block randomized design in strip-plot. #' library(AgroR) #' data(tomate) #' with(tomate, STRIPLOT(parc, subp, bloco, resp)) STRIPLOT=function(f1, f2, block, response, norm="sw", alpha.f=0.05, transf=1, textsize=12, labelsize=4, constant=0){ requireNamespace("crayon") requireNamespace("ggplot2") requireNamespace("nortest") if(transf==1){resp=response}else{resp=(response^transf-1)/transf} if(transf==0){resp=log(response)} if(transf==0.5){resp=sqrt(response)} if(transf==-0.5){resp=1/sqrt(response)} if(transf==-1){resp=1/response} fator1=f1 fator2=f2 fator1a=fator1 fator2a=fator2 bloco=block fac = c("F1", "F2") cont <- c(1, 3) Fator1 <- factor(fator1, levels = unique(fator1)) Fator2 <- factor(fator2, levels = unique(fator2)) bloco <- factor(block) nv1 <- length(summary(Fator1)) nv2 <- length(summary(Fator2)) lf1 <- levels(Fator1) lf2 <- levels(Fator2) num=function(x){as.numeric(x)} graph=data.frame(Fator1,Fator2,resp) mod=aov(resp~f1*f2+f2*block+block:f1) anava=anova(mod) anava=anava[c(3,1,6,2,5,4,7),] anava$`F value`[1]=anava$`Mean Sq`[1]/(anava$`Mean Sq`[3]+anava$`Mean Sq`[5]-anava$`Mean Sq`[7]) anava$`F value`[2]=anava$`Mean Sq`[2]/anava$`Mean Sq`[3] anava$`F value`[4]=anava$`Mean Sq`[4]/anava$`Mean Sq`[5] anava[c(3,5),4:5]=NA anava$`Pr(>F)`[1]=1-pf(anava$`F value`[1],anava$Df[1],anava$Df[3]) anava$`Pr(>F)`[2]=1-pf(anava$`F value`[2],anava$Df[2],anava$Df[3]) anava$`Pr(>F)`[4]=1-pf(anava$`F value`[4],anava$Df[4],anava$Df[5]) rownames(anava)=c("Block","F1","Error A","F2","Error B","F1:F2","Residuals") resids=residuals(mod,scaled=TRUE) Ids=ifelse(resids>3 | resids<(-3), "darkblue","black") residplot=ggplot(data=data.frame(resids,Ids), aes(y=resids,x=1:length(resids)))+ geom_point(shape=21,color="gray",fill="gray",size=3)+ labs(x="",y="Standardized residuals")+ geom_text(x=1:length(resids),label=1:length(resids), color=Ids,size=labelsize)+ scale_x_continuous(breaks=1:length(resids))+ theme_classic()+theme(axis.text.y = element_text(size=textsize), axis.text.x = element_blank())+ geom_hline(yintercept = c(0,-3,3),lty=c(1,2,2),color="red",size=1) # Normalidade dos erros if(norm=="sw"){norm1 = shapiro.test(resid(mod))} if(norm=="li"){norm1=lillie.test(resid(mod))} if(norm=="ad"){norm1=ad.test(resid(mod))} if(norm=="cvm"){norm1=cvm.test(resid(mod))} if(norm=="pearson"){norm1=pearson.test(resid(mod))} if(norm=="sf"){norm1=sf.test(resid(mod))} cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(green(bold("Normality of errors"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) normal=data.frame(Method=paste(norm1$method,"(",names(norm1$statistic),")",sep=""), Statistic=norm1$statistic, "p-value"=norm1$p.value) rownames(normal)="" print(normal) cat("\n") message(if(norm1$p.value>0.05){ black("As the calculated p-value is greater than the 5% significance level, hypothesis H0 is not rejected. Therefore, errors can be considered normal")} else {"As the calculated p-value is less than the 5% significance level, H0 is rejected. Therefore, errors do not follow a normal distribution"}) homog1=bartlett.test(resid(mod)~Fator1) homog2=bartlett.test(resid(mod)~Fator2) homog3=bartlett.test(resid(mod)~paste(Fator1,Fator2)) cat(green(bold("\n\n-----------------------------------------------------------------\n"))) cat(green(bold("Homogeneity of Variances"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(green(bold("Interaction\n"))) statistic3=homog3$statistic phomog3=homog3$p.value method3=paste("Bartlett test","(",names(statistic3),")",sep="") homoge3=data.frame(Method=method3, Statistic=statistic3, "p-value"=phomog3) rownames(homoge3)="" print(homoge3) cat("\n") message(if(homog3$p.value[1]>0.05){ black("As the calculated p-value is greater than the 5% significance level, hypothesis H0 is not rejected. Therefore, the variances can be considered homogeneous")} else {"As the calculated p-value is less than the 5% significance level, H0 is rejected. Therefore, the variances are not homogeneous"}) cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(green(bold("Additional Information"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(paste("\nCV1 (%) = ",round(sqrt(anava$`Mean Sq`[3])/mean(resp,na.rm=TRUE)*100,2))) cat(paste("\nCV2 (%) = ",round(sqrt(anava$`Mean Sq`[5])/mean(resp,na.rm=TRUE)*100,2))) cat(paste("\nCV3 (%) = ",round(sqrt(anava$`Mean Sq`[7])/mean(resp,na.rm=TRUE)*100,2))) cat(paste("\nMean = ",round(mean(response,na.rm=TRUE),4))) cat(paste("\nMedian = ",round(median(response,na.rm=TRUE),4))) #cat("\nPossible outliers = ", out) cat("\n") cat(green(bold("\n\n-----------------------------------------------------------------\n"))) cat(green(bold("Analysis of Variance"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) anava=data.frame(anava) colnames(anava)=c("Df","Sum Sq ","Mean Sq","F value","Pr(>F)") print(as.matrix(anava),na.print="",quote = FALSE) if(transf==1 && norm1$p.value<0.05 | transf==1 &&homog1$p.value<0.05){ message("\n \nYour analysis is not valid, suggests using a try to transform the data\n")}else{} message(if(transf !=1){blue("\nNOTE: resp = transformed means; respO = averages without transforming\n")})}
/scratch/gouwar.j/cran-all/cranData/AgroR/R/stripplot_function.R
#' Utils: Dunnett's Test Summary #' @export #' @description Performs a summary in table form from a list of Dunnett's test outputs #' @param variable List object Dunnett test #' @param colnames Names of column #' @param info Information of table #' @return A summary table from Dunnett's test is returned #' #' @examples #' library(AgroR) #' data("pomegranate") #' a=with(pomegranate,dunnett(trat=trat,resp=WL,control="T1")) #' b=with(pomegranate,dunnett(trat=trat,resp=SS,control="T1")) #' c=with(pomegranate,dunnett(trat=trat,resp=AT,control="T1")) #' d=with(pomegranate,dunnett(trat=trat,resp=ratio,control="T1")) #' summarise_dunnett(list(a,b,c,d)) summarise_dunnett=function(variable, colnames=NA, info="sig"){ variaveis=length(variable) nomes=rownames(variable[[1]]$data) if(is.na(colnames[1])==TRUE){colnames=rep(paste("Var",1:variaveis))} datas=data.frame(matrix(rep(NA,variaveis*length(nomes)),ncol=variaveis)) for(i in 1:variaveis){ if(info=="sig"){datas[,i]=variable[[i]]$data$sig} if(info=="t"){datas[,i]=variable[[i]]$data$t.value} if(info=="p"){datas[,i]=variable[[i]]$data$p.value} if(info=="estimate"){datas[,i]=variable[[i]]$data$Estimate} if(info=="IC.lower"){datas[,i]=variable[[i]]$data$IC.lwr} if(info=="IC.upper"){datas[,i]=variable[[i]]$data$IC.upr} } rownames(datas)=nomes colnames(datas)=colnames datas }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/summarise_dunnett.R
#' Utils: Summary of Analysis of Variance and Test of Means #' @description Summarizes the output of the analysis of variance and the multiple comparisons test for completely randomized (DIC), randomized block (DBC) and Latin square (DQL) designs. #' @author Gabriel Danilo Shimizu #' @param analysis List with the analysis outputs of the DIC, DBC, DQL, FAT2DIC, FAT2DBC, PSUBDIC and PSUBDBC functions #' @param design Type of experimental project (DIC, DBC, DQL, FAT2DIC, FAT2DBC, PSUBDIC or PSUBDBC) #' @param round Number of decimal places #' @param divisor Add divider between columns #' @param inf Analysis of variance information (can be "p", "f", "QM" or "SQ") #' @note Adding table divider can help to build tables in microsoft word. Copy console output, paste into MS Word, Insert, Table, Convert text to table, Separated text into:, Other: |. #' @note The column names in the final output are imported from the ylab argument within each function. #' @note This function is only for declared qualitative factors. In the case of a quantitative factor and the other qualitative in projects with two factors, this function will not work. #' @note Triple factorials and split-split-plot do not work in this function. #' @import knitr #' @export #' @examples #' #' #' library(AgroR) #' #' #===================================== #' # DIC #' #===================================== #' data(pomegranate) #' attach(pomegranate) #' a=DIC(trat, WL, geom = "point", ylab = "WL") #' b=DIC(trat, SS, geom = "point", ylab="SS") #' c=DIC(trat, AT, geom = "point", ylab = "AT") #' summarise_anova(analysis = list(a,b,c), divisor = TRUE) #' library(knitr) #' kable(summarise_anova(analysis = list(a,b,c), divisor = FALSE)) #' #' #===================================== #' vari=c("WL","SS","AT") #' output=lapply(vari,function(x){ #' output=DIC(trat,response = unlist(pomegranate[,x]),ylab = parse(text=x))}) #' summarise_anova(analysis = output, divisor = TRUE) #' #' #===================================== #' # DBC #' #===================================== #' data(soybean) #' attach(soybean) #' a=DBC(cult,bloc,prod,ylab = "Yield") #' summarise_anova(list(a),design = "DBC") #' #' #===================================== #' # FAT2DIC #' #===================================== #' data(corn) #' attach(corn) #' a=FAT2DIC(A, B, Resp, quali=c(TRUE, TRUE)) #' summarise_anova(list(a),design="FAT2DIC") summarise_anova=function(analysis, inf="p", design="DIC", round=3, divisor=TRUE){ requireNamespace("knitr") if(design=="DIC"){ nlinhas=length(analysis[[1]][[1]]$plot$dadosm$groups) infor=data.frame(matrix(ncol=length(analysis),nrow = nlinhas)) trats=analysis[[1]][[1]]$plot$dadosm$trats variable=1:length(analysis) for(i in 1:length(analysis)){ tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab letra=analysis[[i]][[1]]$plot$dadosm$groups transf=analysis[[i]][[1]]$plot$transf if(transf==1){media=round(analysis[[i]][[1]]$plot$dadosm$resp,round)} if(transf!=1){media=round(analysis[[i]][[1]]$plot$dadosm$respO,round)} infor[,i]=paste(media,letra)} if(tests=="noparametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab letra=analysis[[i]][[1]]$plot$dadosm$groups media=round(analysis[[i]][[1]]$plot$dadosm$media,round) infor[,i]=paste(media,letra)} } names(infor)=variable rownames(infor)=trats cvs=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[,i]=round(sqrt(analysis[[i]][[1]]$plot$a$`Mean Sq`[2])/ mean(analysis[[i]][[1]]$plot$resp)*100,round)} if(tests=="noparametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[,i]=" "}} rownames(cvs)="CV(%)" names(cvs)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ tests=analysis[[i]][[1]]$plot$test variable[i]=analysis[[i]][[1]]$plot$ylab if(tests=="parametric"){ tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} if(tests=="noparametric"){ transf[,i]=""} } rownames(transf)="Transformation" names(transf)=variable n=5 nc=1 infor1=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$anava[1,n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} if(tests=="noparametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$krusk$statistics[2],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)}} names(infor1)=variable rownames(infor1)="p-value" n=4 nc=1 infor2=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=round(analysis[[i]][[1]]$plot$anava[1,n],round)} if(tests=="noparametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=paste(round(analysis[[i]][[1]]$plot$krusk$statistics[1][[1]],round), "(Chisq)")}} names(infor2)=variable rownames(infor2)="F" n=3 nc=2 infor3=data.frame(matrix(ncol=length(analysis),nrow = 2)) variable=1:length(analysis) for(i in 1:length(analysis)){ tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} if(tests=="noparametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=""} } names(infor3)=variable rownames(infor3)=c("QM_tr","QM_r") n=2 nc=2 infor4=data.frame(matrix(ncol=length(analysis),nrow = 2)) variable=1:length(analysis) for(i in 1:length(analysis)){ tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} if(tests=="noparametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=""}} names(infor4)=variable rownames(infor4)=c("SQ_tr","SQ_r") if(inf=="p"){juntos=rbind(infor,cvs,infor1,transf)} if(inf=="f"){juntos=rbind(infor,cvs,infor2,transf)} if(inf=="QM"){juntos=rbind(infor,cvs,infor3,transf)} if(inf=="SQ"){juntos=rbind(infor,cvs,infor4,transf)} if(inf=="all"){juntos=rbind(infor,cvs,infor1,infor2,infor3,infor4,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="DBC"){ nlinhas=length(analysis[[1]][[1]]$plot$dadosm$groups) infor=data.frame(matrix(ncol=length(analysis),nrow = nlinhas)) trats=analysis[[1]][[1]]$plot$dadosm$trats variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ letra=analysis[[i]][[1]]$plot$dadosm$groups transf=analysis[[i]][[1]]$plot$transf if(transf==1){media=round(analysis[[i]][[1]]$plot$dadosm$resp,round)} if(transf!=1){media=round(analysis[[i]][[1]]$plot$dadosm$respO,round)} infor[,i]=paste(media,letra)} if(tests=="noparametric"){ letra=analysis[[i]][[1]]$plot$dadosm$groups media=round(analysis[[i]][[1]]$plot$dadosm$media,round) infor[,i]=paste(media,letra)} } names(infor)=variable rownames(infor)=trats cvs=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ cvs[,i]=round(sqrt(analysis[[i]][[1]]$plot$a$`Mean Sq`[3])/ mean(analysis[[i]][[1]]$plot$resp)*100,round)} if(tests=="noparametric"){ cvs[,i]="-"}} rownames(cvs)="CV(%)" names(cvs)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} if(tests=="noparametric"){transf[,i]="-"}} rownames(transf)="Transformation" names(transf)=variable n=5 nc=2 infor1=data.frame(matrix(ncol=length(analysis),nrow = 2)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ pvalor=round(analysis[[i]][[1]]$plot$anava[1:2,n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} if(tests=="noparametric"){ pvalor=round(analysis[[i]][[1]]$plot$fried$statistics[6],round) infor1[,i]=c(ifelse(pvalor<0.001,"p<0.001",pvalor[[1]]), "-")} } names(infor1)=variable rownames(infor1)=c("p_tr","p_bl") n=4 nc=2 infor2=data.frame(matrix(ncol=length(analysis),nrow = 2)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ infor2[,i]=round(analysis[[i]][[1]]$plot$anava[1:2,n],round)} if(tests=="noparametric"){ infor2[,i]=c(round(analysis[[i]][[1]]$plot$fried$statistics[4][[1]],round), "-")}} names(infor2)=variable rownames(infor2)=c("F_tr","F_bl") n=3 nc=3 infor3=data.frame(matrix(ncol=length(analysis),nrow = 3)) variable=1:length(analysis) for(i in 1:length(analysis)){ tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} if(tests=="noparametric"){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=c("-","-","-")} } names(infor3)=variable rownames(infor3)=c("QM_tr","QM_bl","QM_r") n=2 nc=3 infor4=data.frame(matrix(ncol=length(analysis),nrow = 3)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tests=analysis[[i]][[1]]$plot$test if(tests=="parametric"){ infor4[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} if(tests=="noparametric"){ infor4[,i]=c("-","-","-")}} names(infor4)=variable rownames(infor4)=c("SQ_tr","SQ_bl","SQ_r") if(inf=="p"){juntos=rbind(infor,cvs,infor1,transf)} if(inf=="f"){juntos=rbind(infor,cvs,infor2,transf)} if(inf=="QM"){juntos=rbind(infor,cvs,infor3,transf)} if(inf=="SQ"){juntos=rbind(infor,cvs,infor4,transf)} if(inf=="all"){juntos=rbind(infor,cvs,infor1,infor2,infor3,infor4,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="DQL"){ nlinhas=length(analysis[[1]][[1]]$plot$dadosm$groups) infor=data.frame(matrix(ncol=length(analysis),nrow = nlinhas)) trats=analysis[[1]][[1]]$plot$dadosm$trats variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab letra=analysis[[i]][[1]]$plot$dadosm$groups transf=analysis[[i]][[1]]$plot$transf if(transf==1){media=round(analysis[[i]][[1]]$plot$dadosm$resp,round)} if(transf!=1){media=round(analysis[[i]][[1]]$plot$dadosm$respO,round)} infor[,i]=paste(media,letra) } names(infor)=variable rownames(infor)=trats cvs=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[,i]=round(sqrt(analysis[[i]][[1]]$plot$a$`Mean Sq`[4])/ mean(analysis[[i]][[1]]$plot$resp)*100,round) } rownames(cvs)="CV(%)" names(cvs)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} rownames(transf)="Transformation" names(transf)=variable n=5 nc=3 infor1=data.frame(matrix(ncol=length(analysis),nrow = 3)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} names(infor1)=variable rownames(infor1)=c("p_tr","p_l","p_c") n=4 nc=3 infor2=data.frame(matrix(ncol=length(analysis),nrow = 3)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor2)=variable rownames(infor2)=c("F_tr","F_l","F_c") n=3 nc=4 infor3=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor3)=variable rownames(infor3)=c("QM_tr","QM_l","QM_c","QM_r") n=2 nc=4 infor4=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor4)=variable rownames(infor4)=c("SQ_tr","SQ_l","SQ_c","SQ_r") if(inf=="p"){juntos=rbind(infor,cvs,infor1,transf)} if(inf=="f"){juntos=rbind(infor,cvs,infor2,transf)} if(inf=="QM"){juntos=rbind(infor,cvs,infor3,transf)} if(inf=="SQ"){juntos=rbind(infor,cvs,infor4,transf)} if(inf=="all"){juntos=rbind(infor,cvs,infor1,infor2,infor3,infor4,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="FAT2DIC"){ cvs=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[,i]=round(sqrt(analysis[[i]][[1]]$plot$a$`Mean Sq`[4])/ mean(analysis[[i]][[1]]$plot$resp)*100,round)} rownames(cvs)="CV(%)" names(cvs)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} rownames(transf)="Transformation" names(transf)=variable n=5 nc=3 infor1=data.frame(matrix(ncol=length(analysis),nrow = 3)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} names(infor1)=variable rownames(infor1)=c("p_F1","p_F2","p_F1xF2") n=4 nc=3 infor2=data.frame(matrix(ncol=length(analysis),nrow = 3)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor2)=variable rownames(infor2)=c("f_F1","f_F2","f_F1xF2") n=3 nc=4 infor3=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor3)=variable rownames(infor3)=c("QM_F1","QM_F2","QM_F1xF2","QM_r") n=2 nc=4 infor4=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor4)=variable rownames(infor4)=c("SQ_F1","SQ_F2","SQ_F1xF2","SQ_r") variable=1:length(analysis) nf1=analysis[[1]][[1]]$plot$anava[1,1]+1 nf2=analysis[[1]][[1]]$plot$anava[2,1]+1 nf1f2=nf1*nf2 f1mean=data.frame(matrix(rep("-",(length(analysis)*nf1)),ncol=length(analysis),nrow = nf1)) f2mean=data.frame(matrix(rep("-",(length(analysis)*nf2)),ncol=length(analysis),nrow = nf2)) f1f2mean=data.frame(matrix(rep("-",(length(analysis)*nf1f2)),ncol=length(analysis),nrow = nf1f2)) rownames(f1mean)=unique(analysis[[1]][[1]]$plot$f1) rownames(f2mean)=unique(analysis[[1]][[1]]$plot$f2) nomes=expand.grid(unique(analysis[[1]][[1]]$plot$f2),unique(analysis[[1]][[1]]$plot$f1)) rownames(f1f2mean)=paste(nomes$Var2,nomes$Var1) for(i in 1:length(analysis)){ sigF=analysis[[i]][[1]]$plot$alpha.f variable[i]=analysis[[i]][[1]]$plot$ylab pvalue=round(analysis[[i]][[1]]$plot$anava[1:3,5],round) if(pvalue[3]<sigF){f1f2mean[,i]=data.frame(analysis[[i]][[1]]$plot$graph$numero) rownames(f1f2mean)=rownames(analysis[[i]][[1]]$plot$graph)}else{ if(pvalue[1]<sigF){f1mean[,i]=data.frame(analysis[[i]][[2]]$data$letra) rownames(f1mean)=rownames(analysis[[i]][[2]]$data)} if(pvalue[2]<sigF){f2mean[,i]=data.frame(analysis[[i]][[3]]$data$letra) rownames(f2mean)=rownames(analysis[[i]][[3]]$data)}} } names(f1mean)=variable names(f2mean)=variable names(f1f2mean)=variable # juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,infor2,infor3,infor4,transf) if(inf=="p"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,transf)} if(inf=="f"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor2,transf)} if(inf=="QM"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor3,transf)} if(inf=="SQ"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor4,transf)} if(inf=="all"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,infor2,infor3,infor4,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="FAT2DBC"){ cvs=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[,i]=round(sqrt(analysis[[i]][[1]]$plot$a$`Mean Sq`[5])/ mean(analysis[[i]][[1]]$plot$resp)*100,round)} rownames(cvs)="CV(%)" names(cvs)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} rownames(transf)="Transformation" names(transf)=variable n=5 nc=4 infor1=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} names(infor1)=variable rownames(infor1)=c("p_F1","p_F2","p_bl","p_F1xF2") n=4 nc=4 infor2=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor2)=variable rownames(infor2)=c("f_F1","f_F2","f_bl","f_F1xF2") n=3 nc=5 infor3=data.frame(matrix(ncol=length(analysis),nrow = 5)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor3)=variable rownames(infor3)=c("QM_F1","QM_F2","QM_bl","QM_F1xF2","QM_r") n=2 nc=5 infor4=data.frame(matrix(ncol=length(analysis),nrow = 5)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor4)=variable rownames(infor4)=c("SQ_F1","SQ_F2","SQ_bl","SQ_F1xF2","SQ_r") variable=1:length(analysis) nf1=analysis[[1]][[1]]$plot$anava[1,1]+1 nf2=analysis[[1]][[1]]$plot$anava[2,1]+1 nf1f2=nf1*nf2 f1mean=data.frame(matrix(rep("-",(length(analysis)*nf1)),ncol=length(analysis),nrow = nf1)) f2mean=data.frame(matrix(rep("-",(length(analysis)*nf2)),ncol=length(analysis),nrow = nf2)) f1f2mean=data.frame(matrix(rep("-",(length(analysis)*nf1f2)),ncol=length(analysis),nrow = nf1f2)) rownames(f1mean)=unique(analysis[[1]][[1]]$plot$f1) rownames(f2mean)=unique(analysis[[1]][[1]]$plot$f2) nomes=expand.grid(unique(analysis[[1]][[1]]$plot$f2),unique(analysis[[1]][[1]]$plot$f1)) rownames(f1f2mean)=paste(nomes$Var2,nomes$Var1) for(i in 1:length(analysis)){ sigF=analysis[[i]][[1]]$plot$alpha.f variable[i]=analysis[[i]][[1]]$plot$ylab pvalue=round(analysis[[i]][[1]]$plot$anava[1:4,5],round) if(pvalue[4]<sigF){f1f2mean[,i]=data.frame(analysis[[i]][[1]]$plot$graph$numero) rownames(f1f2mean)=rownames(analysis[[i]][[1]]$plot$graph)}else{ if(pvalue[1]<sigF){f1mean[,i]=data.frame(analysis[[i]][[2]]$data$letra) rownames(f1mean)=rownames(analysis[[i]][[2]]$data)} if(pvalue[2]<sigF){f2mean[,i]=data.frame(analysis[[i]][[3]]$data$letra) rownames(f2mean)=rownames(analysis[[i]][[3]]$data)}} } names(f1mean)=variable names(f2mean)=variable names(f1f2mean)=variable if(inf=="p"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,transf)} if(inf=="f"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor2,transf)} if(inf=="QM"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor3,transf)} if(inf=="SQ"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor4,transf)} if(inf=="all"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,infor2,infor3,infor4,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="PSUBDIC"){ cvs=data.frame(matrix(ncol=length(analysis),nrow = 2)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[1,i]=round(sqrt(analysis[[i]][[1]]$plot$anova1$`Mean Sq`[2])/ mean(analysis[[i]][[1]]$plot$resp)*100,round) cvs[2,i]=round(sqrt(analysis[[i]][[1]]$plot$anova1$`Mean Sq`[5])/ mean(analysis[[i]][[1]]$plot$resp)*100,round)} rownames(cvs)=c("CV1 (%)","CV2 (%)") names(cvs)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} rownames(transf)="Transformation" names(transf)=variable # p-value n=5 infor1=data.frame(matrix(ncol=length(analysis),nrow = 3)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$anova1[c(1,3,4),n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} names(infor1)=variable rownames(infor1)=c("p_F1","p_F2","p_F1xF2") n=4 infor2=data.frame(matrix(ncol=length(analysis),nrow = 3)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=round(analysis[[i]][[1]]$plot$anova1[c(1,3,4),n],round)} names(infor2)=variable rownames(infor2)=c("f_F1","f_F2","f_F1xF2") n=3 infor3=data.frame(matrix(ncol=length(analysis),nrow = 5)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anova1[c(1:5),n],round)} names(infor3)=variable rownames(infor3)=c("QM_F1","QM_error1","QM_F2","QM_F1xF2","QM_error2") n=2 infor4=data.frame(matrix(ncol=length(analysis),nrow = 5)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=round(analysis[[i]][[1]]$plot$anova1[1:5,n],round)} names(infor4)=variable rownames(infor4)=c("SQ_F1","SQ_error1","SQ_F2","SQ_F1xF2","SQ_error2") variable=1:length(analysis) nf1=analysis[[1]][[1]]$plot$anova1[1,1]+1 nf2=analysis[[1]][[1]]$plot$anova1[3,1]+1 nf1f2=nf1*nf2 f1mean=data.frame(matrix(rep("-",(length(analysis)*nf1)),ncol=length(analysis),nrow = nf1)) f2mean=data.frame(matrix(rep("-",(length(analysis)*nf2)),ncol=length(analysis),nrow = nf2)) f1f2mean=data.frame(matrix(rep("-",(length(analysis)*nf1f2)),ncol=length(analysis),nrow = nf1f2)) rownames(f1mean)=unique(analysis[[1]][[1]]$plot$f1) rownames(f2mean)=unique(analysis[[1]][[1]]$plot$f2) nomes=expand.grid(unique(analysis[[1]][[1]]$plot$f2),unique(analysis[[1]][[1]]$plot$f1)) rownames(f1f2mean)=paste(nomes$Var2,nomes$Var1) for(i in 1:length(analysis)){ sigF=analysis[[i]][[1]]$plot$alpha.f variable[i]=analysis[[i]][[1]]$plot$ylab pvalue=round(analysis[[i]][[1]]$plot$anova1[c(1,3,4),5],round) if(pvalue[3]<0.05){f1f2mean[,i]=data.frame(analysis[[i]][[1]]$plot$graph$numero) rownames(f1f2mean)=rownames(analysis[[i]][[1]]$plot$graph)}else{ if(pvalue[1]<0.05){f1mean[,i]=data.frame(analysis[[i]][[2]]$data$letra) rownames(f1mean)=rownames(analysis[[i]][[2]]$data)} if(pvalue[2]<0.05){f2mean[,i]=data.frame(analysis[[i]][[3]]$data$letra) rownames(f2mean)=rownames(analysis[[i]][[3]]$data)}} } names(f1mean)=variable names(f2mean)=variable names(f1f2mean)=variable if(inf=="p"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,transf)} if(inf=="f"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor2,transf)} if(inf=="QM"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor3,transf)} if(inf=="SQ"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor4,transf)} if(inf=="all"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,infor2,infor3,infor4,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="PSUBDBC"){ cvs=data.frame(matrix(ncol=length(analysis),nrow = 2)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[1,i]=round(sqrt(analysis[[i]][[1]]$plot$anova1$`Mean Sq`[3])/ mean(analysis[[i]][[1]]$plot$resp)*100,round) cvs[2,i]=round(sqrt(analysis[[i]][[1]]$plot$anova1$`Mean Sq`[6])/ mean(analysis[[i]][[1]]$plot$resp)*100,round)} rownames(cvs)=c("CV1 (%)","CV2 (%)") names(cvs)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} rownames(transf)="Transformation" names(transf)=variable # p-value n=5 infor1=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$anova1[c(1,2,4,5),n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} names(infor1)=variable rownames(infor1)=c("p_F1","p_bl","p_F2","p_F1xF2") n=4 infor2=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=round(analysis[[i]][[1]]$plot$anova1[c(1,2,4,5),n],round)} names(infor2)=variable rownames(infor2)=c("f_F1","f_bl","f_F2","f_F1xF2") n=3 infor3=data.frame(matrix(ncol=length(analysis),nrow = 6)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anova1[c(1:6),n],round)} names(infor3)=variable rownames(infor3)=c("QM_F1","QM_bl","QM_error1","QM_F2","QM_F1xF2","QM_error2") n=2 infor4=data.frame(matrix(ncol=length(analysis),nrow = 6)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=round(analysis[[i]][[1]]$plot$anova1[1:6,n],round)} names(infor4)=variable rownames(infor4)=c("SQ_F1","SQ_bl","SQ_error1","SQ_F2","SQ_F1xF2","SQ_error2") variable=1:length(analysis) nf1=analysis[[1]][[1]]$plot$anova1[1,1]+1 nf2=analysis[[1]][[1]]$plot$anova1[4,1]+1 nf1f2=nf1*nf2 f1mean=data.frame(matrix(rep("-",(length(analysis)*nf1)),ncol=length(analysis),nrow = nf1)) f2mean=data.frame(matrix(rep("-",(length(analysis)*nf2)),ncol=length(analysis),nrow = nf2)) f1f2mean=data.frame(matrix(rep("-",(length(analysis)*nf1f2)),ncol=length(analysis),nrow = nf1f2)) rownames(f1mean)=unique(analysis[[1]][[1]]$plot$f1) rownames(f2mean)=unique(analysis[[1]][[1]]$plot$f2) nomes=expand.grid(unique(analysis[[1]][[1]]$plot$f2),unique(analysis[[1]][[1]]$plot$f1)) rownames(f1f2mean)=paste(nomes$Var2,nomes$Var1) for(i in 1:length(analysis)){ sigF=analysis[[i]][[1]]$plot$alpha.f variable[i]=analysis[[i]][[1]]$plot$ylab pvalue=round(analysis[[i]][[1]]$plot$anova1[c(1,4,5),5],round) if(pvalue[3]<0.05){f1f2mean[,i]=data.frame(analysis[[i]][[1]]$plot$graph$numero) rownames(f1f2mean)=rownames(analysis[[i]][[1]]$plot$graph)}else{ if(pvalue[1]<0.05){f1mean[,i]=data.frame(analysis[[i]][[2]]$data$letra) rownames(f1mean)=rownames(analysis[[i]][[2]]$data)} if(pvalue[2]<0.05){f2mean[,i]=data.frame(analysis[[i]][[3]]$data$letra) rownames(f2mean)=rownames(analysis[[i]][[3]]$data)}} } names(f1mean)=variable names(f2mean)=variable names(f1f2mean)=variable if(inf=="p"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,transf)} if(inf=="f"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor2,transf)} if(inf=="QM"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor3,transf)} if(inf=="SQ"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor4,transf)} if(inf=="all"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,infor2,infor3,infor4,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="FAT2DBC.ad"){ cvs=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[,i]=round(sqrt(analysis[[i]][[1]]$plot$anava$`Mean Sq`[6])/ mean(c(analysis[[i]][[1]]$plot$resp, analysis[[i]][[1]]$plot$respAd))*100,round)} rownames(cvs)="CV(%)" names(cvs)=variable respAd=data.frame(matrix(ncol=length(analysis),nrow = 2)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab respAd[1,i]=round(mean(analysis[[i]][[1]]$plot$response),round) respAd[2,i]=round(mean(analysis[[i]][[1]]$plot$responseAd),round)} rownames(respAd)=c("Factorial","RespAd") names(respAd)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} rownames(transf)="Transformation" names(transf)=variable n=5 nc=5 infor1=data.frame(matrix(ncol=length(analysis),nrow = 5)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} names(infor1)=variable rownames(infor1)=c("p_F1","p_F2","p_bl","p_F1xF2","p_Fat x Ad") n=4 nc=5 infor2=data.frame(matrix(ncol=length(analysis),nrow = 5)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor2)=variable rownames(infor2)=c("f_F1","f_F2","f_bl","f_F1xF2","f_Fat x Ad") n=3 nc=6 infor3=data.frame(matrix(ncol=length(analysis),nrow = 6)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor3)=variable rownames(infor3)=c("QM_F1","QM_F2","SQ_bl","QM_F1xF2","QM_Fat x Ad","QM_r") n=2 nc=6 infor4=data.frame(matrix(ncol=length(analysis),nrow = 6)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor4)=variable rownames(infor4)=c("SQ_F1","SQ_F2","SQ_bl","SQ_F1xF2","SQ_Fat x Ad","SQ_r") variable=1:length(analysis) nf1=analysis[[1]][[1]]$plot$anava[1,1]+1 nf2=analysis[[1]][[1]]$plot$anava[2,1]+1 nf1f2=nf1*nf2 f1mean=data.frame(matrix(rep("-",(length(analysis)*nf1)),ncol=length(analysis),nrow = nf1)) f2mean=data.frame(matrix(rep("-",(length(analysis)*nf2)),ncol=length(analysis),nrow = nf2)) f1f2mean=data.frame(matrix(rep("-",(length(analysis)*nf1f2)),ncol=length(analysis),nrow = nf1f2)) rownames(f1mean)=unique(analysis[[1]][[1]]$plot$f1) rownames(f2mean)=unique(analysis[[1]][[1]]$plot$f2) nomes=expand.grid(unique(analysis[[1]][[1]]$plot$f2),unique(analysis[[1]][[1]]$plot$f1)) rownames(f1f2mean)=paste(nomes$Var2,nomes$Var1) for(i in 1:length(analysis)){ sigF=analysis[[i]][[1]]$plot$alpha.f variable[i]=analysis[[i]][[1]]$plot$ylab pvalue=round(analysis[[i]][[1]]$plot$anava[1:4,5],round) if(pvalue[4]<sigF){f1f2mean[,i]=data.frame(analysis[[i]][[1]]$plot$graph$numero) rownames(f1f2mean)=rownames(analysis[[i]][[1]]$plot$graph)}else{ if(pvalue[1]<sigF){f1mean[,i]=data.frame(analysis[[i]][[2]]$data$letra) rownames(f1mean)=rownames(analysis[[i]][[2]]$data)} if(pvalue[2]<sigF){f2mean[,i]=data.frame(analysis[[i]][[3]]$data$letra) rownames(f2mean)=rownames(analysis[[i]][[3]]$data)}} } names(f1mean)=variable names(f2mean)=variable names(f1f2mean)=variable if(inf=="p"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,respAd,transf)} if(inf=="f"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor2,respAd,transf)} if(inf=="QM"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor3,respAd,transf)} if(inf=="SQ"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor4,respAd,transf)} if(inf=="all"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,infor2,infor3,infor4,respAd,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="FAT2DIC.ad"){ cvs=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab cvs[,i]=round(sqrt(analysis[[i]][[1]]$plot$anava$`Mean Sq`[5])/ mean(c(analysis[[i]][[1]]$plot$resp, analysis[[i]][[1]]$plot$respAd))*100,round)} rownames(cvs)="CV(%)" names(cvs)=variable respAd=data.frame(matrix(ncol=length(analysis),nrow = 2)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab respAd[1,i]=round(mean(analysis[[i]][[1]]$plot$response),round) respAd[2,i]=round(mean(analysis[[i]][[1]]$plot$responseAd),round)} rownames(respAd)=c("Factorial","RespAd") names(respAd)=variable transf=data.frame(matrix(ncol=length(analysis),nrow = 1)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab tran=analysis[[i]][[1]]$plot$transf if(tran==1){tran=1}else{tran=tran} if(tran==0){tran="log"} if(tran==0.5){tran="sqrt(x)"} if(tran==-0.5){tran="1/sqrt(x)"} if(tran==-1){tran="1/x"} transf[,i]=ifelse(tran==1,"No transf",tran)} rownames(transf)="Transformation" names(transf)=variable n=5 nc=4 infor1=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab pvalor=round(analysis[[i]][[1]]$plot$anava[1:4,n],round) infor1[,i]=ifelse(pvalor<0.001,"p<0.001",pvalor)} names(infor1)=variable rownames(infor1)=c("p_F1","p_F2","p_F1xF2","p_Fat x Ad") n=4 nc=4 infor2=data.frame(matrix(ncol=length(analysis),nrow = 4)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor2[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor2)=variable rownames(infor2)=c("f_F1","f_F2","f_F1xF2", "f_Fat x Ad") n=3 nc=5 infor3=data.frame(matrix(ncol=length(analysis),nrow = 5)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor3[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor3)=variable rownames(infor3)=c("QM_F1","QM_F2","QM_F1xF2","QM_Fat x Ad","QM_r") n=2 nc=5 infor4=data.frame(matrix(ncol=length(analysis),nrow = 5)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]][[1]]$plot$ylab infor4[,i]=round(analysis[[i]][[1]]$plot$anava[1:nc,n],round)} names(infor4)=variable rownames(infor4)=c("SQ_F1","SQ_F2","SQ_F1xF2","SQ_Fat x Ad","SQ_r") variable=1:length(analysis) nf1=analysis[[1]][[1]]$plot$anava[1,1]+1 nf2=analysis[[1]][[1]]$plot$anava[2,1]+1 nf1f2=nf1*nf2 f1mean=data.frame(matrix(rep("-",(length(analysis)*nf1)),ncol=length(analysis),nrow = nf1)) f2mean=data.frame(matrix(rep("-",(length(analysis)*nf2)),ncol=length(analysis),nrow = nf2)) f1f2mean=data.frame(matrix(rep("-",(length(analysis)*nf1f2)),ncol=length(analysis),nrow = nf1f2)) rownames(f1mean)=unique(analysis[[1]][[1]]$plot$f1) rownames(f2mean)=unique(analysis[[1]][[1]]$plot$f2) nomes=expand.grid(unique(analysis[[1]][[1]]$plot$f2),unique(analysis[[1]][[1]]$plot$f1)) rownames(f1f2mean)=paste(nomes$Var2,nomes$Var1) for(i in 1:length(analysis)){ sigF=analysis[[i]][[1]]$plot$alpha.f variable[i]=analysis[[i]][[1]]$plot$ylab pvalue=round(analysis[[i]][[1]]$plot$anava[1:3,5],round) if(pvalue[3]<sigF){f1f2mean[,i]=data.frame(analysis[[i]][[1]]$plot$graph$numero) rownames(f1f2mean)=rownames(analysis[[i]][[1]]$plot$graph)}else{ if(pvalue[1]<sigF){f1mean[,i]=data.frame(analysis[[i]][[2]]$data$letra) rownames(f1mean)=rownames(analysis[[i]][[2]]$data)} if(pvalue[2]<sigF){f2mean[,i]=data.frame(analysis[[i]][[3]]$data$letra) rownames(f2mean)=rownames(analysis[[i]][[3]]$data)}} } names(f1mean)=variable names(f2mean)=variable names(f1f2mean)=variable if(inf=="p"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,respAd,transf)} if(inf=="f"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor2,respAd,transf)} if(inf=="QM"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor3,respAd,transf)} if(inf=="SQ"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor4,respAd,transf)} if(inf=="all"){juntos=rbind(f1mean,f2mean,f1f2mean,cvs,infor1,infor2,infor3,infor4,respAd,transf)} if(divisor==TRUE){ nl=nrow(juntos) nc=ncol(juntos) market=data.frame(matrix(rep("|",nl*nc),ncol=nc,nrow = nl)) juntosnovo=cbind("|"=rep("|",nl),juntos,market) for(i in 1:nc){ ordem=matrix(1:(nc*2),nrow=2) nomes=colnames(juntos) juntosnovo[,c(ordem[,i]+1)]=cbind(juntos[,i],market[,i]) colnames(juntosnovo)[1]="|" colnames(juntosnovo)[c(ordem[,i]+1)]=c(nomes[i],"|")} juntos=juntosnovo} } if(design=="dunnett"){ nlinhas=length(analysis[[1]]$plot$teste[,1]) trats=rownames(analysis[[1]]$plot$data) infor=data.frame(matrix(ncol=length(analysis),nrow = nlinhas)) variable=1:length(analysis) for(i in 1:length(analysis)){ variable[i]=analysis[[i]]$plot$label infor[i]=analysis[[i]]$plot$teste[6]} names(infor)=variable rownames(infor)=trats juntos=infor} # print(juntos) list(juntos)[[1]] }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/summarise_function.R
#' Descriptive: Table descritive analysis #' @description Function for generating a data.frame with averages or other descriptive measures grouped by a categorical variable #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param data data.frame containing the first column with the categorical variable and the remaining response columns #' @param fun Function of descriptive statistics (default is mean) #' @return Returns a data.frame with a measure of dispersion or position from a dataset and separated by a factor #' @keywords descriptive #' @export #' @examples #' data(pomegranate) #' tabledesc(pomegranate) #' library(knitr) #' kable(tabledesc(pomegranate)) tabledesc=function(data, fun=mean){ dados=data[,-1] trat=as.vector(unlist(data[,1])) n=nlevels(as.factor(trat)) nr=ncol(dados)-1 medias=data.frame(matrix(1:(n*nr),ncol = nr)) for(i in 1:ncol(dados)){ medias[,i]=tapply(as.vector(unlist(dados[,i])), trat, fun, na.rm=TRUE)[unique(trat)]} colnames(medias)=colnames(dados) rownames(medias)=unique(trat) print(medias)}
/scratch/gouwar.j/cran-all/cranData/AgroR/R/tabledesc_function.R
#' Graph: Reverse graph of DICT, DBCT and DQL output when geom="bar" #' #' @description The function performs the construction of a reverse graph on the output of DICT, DBCT and DQL when geom="bar". #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param plot.t DICT, DBCT or DQLT output when geom="bar" #' @note All layout and subtitles are imported from DICT, DBCT and DQLT functions #' @keywords Experimental #' @seealso \link{DICT}, \link{DBCT}, \link{DQLT} #' @return Returns a reverse graph of the output of DICT, DBCT or DQLT when geom="bar". #' @export #' @examples #' data(simulate1) #' a=with(simulate1, DICT(trat, tempo, resp,geom="bar",sup=40)) #' TBARPLOT.reverse(a) TBARPLOT.reverse=function(plot.t){ a=plot.t colo=a$plot$fill sup=a$plot$sup labelsize=a$plot$labelsize family=a$plot$family a=plot.t a$data$trat=factor(a$data$trat,unique(a$data$trat)) trat=a$data$trat media=a$data$media desvio=a$data$desvio time=a$data$time letra=a$data$letra graph=ggplot(a$data, aes(x=trat,y=media,fill=time))+ geom_col(position = position_dodge(), color="black")+ a$theme+ ylab(a$plot$ylab)+ xlab(a$plot$xlab)+ labs(fill=a$labels$fill)+ geom_errorbar(aes(ymin=media-desvio,ymax=media+desvio), position = position_dodge(0.90),width=0.5)+ geom_text(aes(label=letra,y=media+desvio+sup), position = position_dodge(0.90),size=labelsize, family=family) if(colo=="gray"){graph=graph+scale_fill_grey()} graph }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/tbarplotreverse_function.R
#' Analysis: Test for two samples #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @description Test for two samples (paired and unpaired t test, paired and unpaired Wilcoxon test) #' @param trat Categorical vector with the two treatments #' @param resp Numeric vector with the response #' @param test Test used (t for test t or w for Wilcoxon test) #' @param alternative A character string specifying the alternative hypothesis, must be one of "two.sided" (default), "greater" or "less". You can specify just the initial letter. #' @param paired A logical indicating whether you want a paired t-test. #' @param correct A logical indicating whether to apply continuity correction in the normal approximation for the p-value. #' @param var.equal A logical variable indicating whether to treat the two variances as being equal. If TRUE then the pooled variance is used to estimate the variance otherwise the Welch (or Satterthwaite) approximation to the degrees of freedom is used. #' @param conf.level Confidence level of the interval. #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param pointsize Point size #' @param yposition.p Position p-value in y #' @param xposition.p Position p-value in x #' @param fill fill box #' @details Alternative = "greater" is the alternative that x has a larger mean than y. For the one-sample case: that the mean is positive. #' @details If paired is TRUE then both x and y must be specified and they must be the same length. Missing values are silently removed (in pairs if paired is TRUE). If var.equal is TRUE then the pooled estimate of the variance is used. By default, if var.equal is FALSE then the variance is estimated separately for both groups and the Welch modification to the degrees of freedom is used. #' @details If the input data are effectively constant (compared to the larger of the two means) an error is generated. #' @return Returns the test for two samples (paired or unpaired t test, paired or unpaired Wilcoxon test) #' @export #' @examples #' resp=rnorm(100,100,5) #' trat=rep(c("A","B"),e=50) #' test_two(trat,resp) #' test_two(trat,resp,paired = TRUE) test_two=function(trat, resp, paired = FALSE, correct = TRUE, test = "t", alternative = c("two.sided", "less", "greater"), conf.level = 0.95, theme = theme_classic(), ylab = "Response", xlab = "", var.equal = FALSE, pointsize = 2, yposition.p=NA, xposition.p=NA, fill = "white"){ if(test=="t" & isTRUE(paired)==FALSE){teste = t.test( resp ~ trat, correct = correct, alternative = alternative, conf.level = conf.level, var.equal = var.equal)} if(test=="t" & isTRUE(paired)==TRUE){ teste=t.test(Pair(resp[trat==unique(trat)[1]], resp[trat==unique(trat)[2]])~1, alternative = alternative, conf.level = conf.level, correct = correct, exact = FALSE)} if(test=="w"& isTRUE(paired)==FALSE){teste=wilcox.test(resp~trat, alternative = alternative, conf.level = conf.level, correct = correct, var.equal = var.equal, exact = FALSE)} if(test=="w" & isTRUE(paired)==TRUE){teste=wilcox.test(Pair(resp[trat==unique(trat)[1]], resp[trat==unique(trat)[2]])~1, alternative = alternative, conf.level = conf.level, correct = correct, exact = FALSE)} dados=data.frame(resp,trat) media=data.frame(media=tapply(resp,trat,mean, na.rm=TRUE)) media$trat=rownames(media) pvalor=sprintf("italic(\"p-value\")==%0.3f",teste$p.value) requireNamespace("ggplot2") grafico=ggplot(dados,aes(y=resp,x=trat))+ geom_boxplot(size=0.8,outlier.colour = "white", fill=fill)+ geom_jitter(width=0.1,alpha=0.2,size=pointsize)+ stat_boxplot(geom="errorbar", linewidth=0.8,width=0.2)+ geom_label(data=media,aes(y=media, x=trat, label=round(media,2)),fill="lightyellow")+ theme+ylab(ylab)+xlab(xlab)+ theme(axis.text = element_text(size=12,color="black")) if(is.na(yposition.p)==TRUE){yposition.p=min(resp)} if(is.na(xposition.p)==TRUE){xposition.p=1.5} if(teste$p.value<0.001){grafico=grafico+ annotate(geom="text", x=xposition.p,y=yposition.p,hjust=0.5,vjust=0, label="italic(\"p-value <0.001\")",parse=TRUE)} if(teste$p.value>0.001){grafico=grafico+ annotate(geom="text",x=xposition.p,y=yposition.p,hjust=0.5,vjust=0, label=pvalor,parse=TRUE)} print(teste) print(grafico) graficos=list(grafico)[[1]] }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/test_two_function.R
#' Graph: Line chart #' #' @description Performs a descriptive line graph with standard deviation bars #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param time Vector containing the x-axis values #' @param response Vector containing the y-axis values #' @param factor Vector containing a categorical factor #' @param errorbar Error bars (sd or se) #' @param legend.position Legend position #' @param ylab y axis title #' @param xlab x axis title #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @seealso \link{radargraph}, \link{sk_graph}, \link{plot_TH}, \link{corgraph}, \link{spider_graph} #' @return Returns a line chart with error bars #' @export #' @examples #' dose=rep(c(0,2,4,6,8,10),e=3,2) #' resp=c(seq(1,18,1),seq(2,19,1)) #' fator=rep(c("A","B"),e=18) #' line_plot(dose,resp,fator) line_plot=function(time, response, factor=NA, errorbar="sd", ylab="Response", xlab="Time", legend.position="right", theme=theme_classic()){ requireNamespace("ggplot2") time=as.numeric(as.character(time)) if(is.na(factor[1])==FALSE){ factor=as.factor(factor) media=tapply(response,list(time,factor), mean, na.rm=TRUE) if(errorbar=="sd"){erro=tapply(response,list(time,factor), sd, na.rm=TRUE)} if(errorbar=="se"){erro=tapply(response,list(time,factor), sd, na.rm=TRUE)/ sqrt(tapply(response,list(time,factor), length, na.rm=TRUE))} dados=data.frame(time=as.numeric(as.character(rep(rownames(erro),length(levels(factor))))), factor=rep(colnames(erro),e=length(unique(time))), response=c(media), erro=c(erro)) graph=ggplot(dados,aes(x=time,y=response,color=factor, fill=factor,group=factor))+ geom_errorbar(aes(ymax=response+erro, ymin=response-erro), size=0.8, width=0.3)+ geom_point(size=4,color="black",shape=21)+ geom_line(size=1)+ theme+theme(axis.text = element_text(size=12,color="black"), axis.title = element_text(size=13), legend.text = element_text(size=12), legend.title = element_text(size=13), legend.position = legend.position)+ xlab(xlab)+ylab(ylab) print(graph)} if(is.na(factor[1])==TRUE){ media=tapply(response,time, mean, na.rm=TRUE) if(errorbar=="sd"){erro=tapply(response,time, sd, na.rm=TRUE)} if(errorbar=="se"){erro=tapply(response,time, sd, na.rm=TRUE)/sqrt(tapply(response,time, length, na.rm=TRUE))} dados=data.frame(time=as.numeric(as.character(names(erro))), response=c(media), erro=c(erro)) graph=ggplot(dados,aes(x=time, y=response))+ geom_errorbar(aes(ymax=response+erro,ymin=response-erro), width=0.3,size=0.8)+ geom_line(size=1)+ geom_point(size=5,fill="gray",color="black",shape=21)+ theme_bw()+theme(axis.text = element_text(size=12,color="black"), axis.title = element_text(size=13))+ xlab(xlab)+ylab(ylab) print(graph)} graphs=as.list(graph) }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/time_plot_function.R
#' Dataset: Tomato data #' #' An experiment conducted in a randomized block design in a split #' plot scheme was developed in order to evaluate the efficiency of #' bacterial isolates in the development of tomato cultivars. The #' experiment counted a total of 24 trays; each block (in a total #' of four blocks), composed of 6 trays, in which each tray contained #' a treatment (6 isolates). Each tray was seeded with 4 different #' genotypes, each genotype occupying 28 cells per tray. The trays #' were randomized inside each block and the genotypes were randomized #' inside each tray. #' @docType data #' #' @usage data(tomate) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{parc}}{Categorical vector with plot} #' \item{\code{subp}}{Categorical vector with split-plot} #' \item{\code{bloco}}{Categorical vector with block} #' \item{\code{resp}}{Numeric vector} #' } #' @keywords datasets #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{weather}, \link{aristolochia}, \link{phao}, \link{passiflora} #' @examples #' data(tomate) "tomate"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/tomate.R
#' Analysis: t test to compare means with a reference value #' #' @description Sometimes the researcher wants to test whether the treatment mean is greater than/equal to or less than a reference value. For example, I want to know if the average productivity of my treatment is higher than the average productivity of a given country. For this, this function allows comparing the means with a reference value using the t test. #' @author Gabriel Danilo Shimizu #' @param response Numerical vector containing the response of the experiment. #' @param trat Numerical or complex vector with treatments #' @param mu A number indicating the true value of the mean #' @param alternative A character string specifying the alternative hypothesis, must be one of "two.sided" (default), "greater" or "less" #' @param conf.level confidence level of the interval. #' @importFrom gridExtra grid.arrange #' @export #' @return returns a list with the mean per treatment, maximum, minimum, sample standard deviation, confidence interval, t-test statistic and its p-value. #' @note No treatment can have zero variability. Otherwise the function will result in an error. #' @examples #' library(AgroR) #' data("pomegranate") #' tonetest(resp=pomegranate$WL, #' trat=pomegranate$trat, #' mu=2, #' alternative = "greater") tonetest=function(response, trat, mu=0, alternative="two.sided", conf.level=0.95){ trat=factor(trat,unique(trat)) nl=nlevels(trat) teste=c(1:nl) inferior=c(1:nl) superior=c(1:nl) estatistica=c(1:nl) minimo=c(1:nl) maximo=c(1:nl) media=c(1:nl) std=c(1:nl) for(i in 1:nl){ test=t.test(response[trat==levels(trat)[i]], mu=mu, alternative = alternative,conf.level=conf.level) media[i]=mean(response[trat==levels(trat)[i]]) std[i]=sd(response[trat==levels(trat)[i]]) minimo[i]=min(response[trat==levels(trat)[i]]) maximo[i]=max(response[trat==levels(trat)[i]]) teste[i]=test$p.value inferior[i]=test$conf.int[1] superior[i]=test$conf.int[2] estatistica[i]=test$statistic} names(teste)=levels(trat) names(inferior)=levels(trat) names(superior)=levels(trat) names(estatistica)=levels(trat) names(media)=levels(trat) names(std)=levels(trat) names(minimo)=levels(trat) names(maximo)=levels(trat) list("mean.ref"=mu, "mean"=media, "sd"=std, "min"=minimo, "max"=maximo, "Statistic"=estatistica, "p.value"=teste, "conf.inf"=inferior, "conf.sup"=superior)}
/scratch/gouwar.j/cran-all/cranData/AgroR/R/tonetest_function.R
#' Utils: Data transformation (Box-Cox, 1964) #' #' @description Estimates the lambda value for data transformation #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @author Rodrigo Yudi Palhaci Marubayashi #' @param response Numerical vector containing the response of the experiment. #' @param f1 Numeric or complex vector with factor 1 levels #' @param f2 Numeric or complex vector with factor 2 levels #' @param f3 Numeric or complex vector with factor 3 levels #' @param block Numerical or complex vector with blocks #' @param line Numerical or complex vector with lines #' @param column Numerical or complex vector with columns #' @keywords Transformation #' @keywords Experimental #' @export #' @return Returns the value of lambda and/or data transformation approximation, according to Box-Cox (1964) #' @references #' #' Box, G. E., Cox, D. R. (1964). An analysis of transformations. Journal of the Royal Statistical Society: Series B (Methodological), 26(2), 211-243. #' @examples #' #' #================================================================ #' # Completely randomized design #' #================================================================ #' data("pomegranate") #' with(pomegranate, transf(WL,f1=trat)) #' #' #================================================================ #' # Randomized block design #' #================================================================ #' data(soybean) #' with(soybean, transf(prod, f1=cult, block=bloc)) #' #' #================================================================ #' # Completely randomized design in double factorial #' #================================================================ #' data(cloro) #' with(cloro, transf(resp, f1=f1, f2=f2)) #' #' #================================================================ #' # Randomized block design in double factorial #' #================================================================ #' data(cloro) #' with(cloro, transf(resp, f1=f1, f2=f2, block=bloco)) transf=function(response, f1, f2=NA, f3=NA, block=NA, line=NA, column=NA){ # DIC simples requireNamespace("MASS") if(is.na(f2[1])==TRUE && is.na(f3[1])==TRUE && is.na(block[1])==TRUE && is.na(line[1])==TRUE && is.na(column[1])==TRUE){ vero=MASS::boxcox(response~f1)} # DBC simples if(is.na(f2[1])==TRUE && is.na(f3[1])==TRUE && is.na(block[1])==FALSE && is.na(line[1])==TRUE && is.na(column[1])==TRUE){ vero=MASS::boxcox(response~f1+block)} # DQL if(is.na(f2[1])==TRUE && is.na(f3[1])==TRUE && is.na(block[1])==TRUE && is.na(line[1])==FALSE && is.na(column[1])==FALSE){ vero=MASS::boxcox(response~f1+column+line)} # fat2.dic if(is.na(f2[1])==FALSE && is.na(f3[1])==TRUE && is.na(block[1])==TRUE && is.na(line[1])==TRUE && is.na(column[1])==TRUE){ vero=MASS::boxcox(response~f1*f2)} #fat2dbc if(is.na(f2[1])==FALSE && is.na(f3[1])==TRUE && is.na(block[1])==FALSE && is.na(line[1])==TRUE && is.na(column[1])==TRUE){ vero=MASS::boxcox(response~f1*f2+block)} # fat3dic if(is.na(f2[1])==FALSE && is.na(f3[1])==FALSE && is.na(block[1])==TRUE && is.na(line[1])==TRUE && is.na(column[1])==TRUE){ vero=MASS::boxcox(response~f1*f2*f3)} # fat3dic if(is.na(f2[1])==FALSE && is.na(f3[1])==FALSE && is.na(block[1])==FALSE && is.na(line[1])==TRUE && is.na(column[1])==TRUE){ vero=MASS::boxcox(response~f1*f2*f3+block)} maxvero = vero$x[which.max(vero$y)] cat("\n------------------------------------------------\n") cat("Box-Cox Transformation (1964)\n") cat("\nLambda=") cat(lambda=maxvero) cat("\n------------------------------------------------\n") cat("Suggestion:\n") cat(if(round(maxvero,2)>0.75 & round(maxvero,2)<1.25){"Do not transform data"} else{if(round(maxvero,2)>0.25 & round(maxvero,2)<=0.75){"square root (sqrt(Y))"} else{if(round(maxvero,2)>-0.75 & round(maxvero,2)<=-0.25){"1/sqrt(Y)"} else{if(round(maxvero,2)>-1.25 & round(maxvero,2)<=-0.75){"1/Y"} else{if(round(maxvero,2)>=-0.25 & round(maxvero,2)<0.25){"log(Y)"}}}}} ) cat("\n\n") cat("ou:") cat("Yt=(Y^lambda-1)/lambda") }
/scratch/gouwar.j/cran-all/cranData/AgroR/R/transf_function.R
#' Dataset: Weather data #' #' @docType data #' #' @description Climatic data from 01 November 2019 to 30 June 2020 in the municipality of Londrina-PR, Brazil. Data from the Instituto de Desenvolvimento Rural do Parana (IDR-PR) #' #' @usage data(weather) #' #' @format data.frame containing data set #' \describe{ #' \item{\code{Data}}{POSIXct vector with dates} #' \item{\code{tempo}}{Numeric vector with time} #' \item{\code{Tmax}}{Numeric vector with maximum temperature} #' \item{\code{Tmed}}{Numeric vector with mean temperature} #' \item{\code{Tmin}}{Numeric vector with minimum temperature} #' \item{\code{UR}}{Numeric vector with relative humidity} #' } #' @keywords datasets #' @seealso \link{cloro}, \link{enxofre}, \link{laranja}, \link{mirtilo}, \link{pomegranate}, \link{porco}, \link{sensorial}, \link{simulate1}, \link{simulate2}, \link{simulate3}, \link{tomate}, \link{aristolochia}, \link{phao}, \link{passiflora} #' @examples #' data(weather) "weather"
/scratch/gouwar.j/cran-all/cranData/AgroR/R/weather.R
#' Analysis: Avhad and Marchetti #' #' This function performs Avhad and Marchetti regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param initial Starting estimates #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param fontfamily Font family #' @param comment Add text after equation #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The Avhad e Marchetti model is defined by: #' \deqn{y = \alpha \times e^{kx^n}} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Avhad, M. R., & Marchetti, J. M. (2016). Mathematical modelling of the drying kinetics of Hass avocado seeds. Industrial Crops and Products, 91, 76-87. #' @export #' #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' AM(time,100-WL,initial=list(alpha = 610.9129, k=-1.1810, n=0.1289 )) AM=function(trat, resp, initial = list(alpha, k, n), sample.curve=1000, ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) alpha=initial$alpha k=initial$k n=initial$n model = nls(resp ~ alpha * exp(k * trat^n), start = initial) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 = nls(ymean ~ alpha * exp(k * xmean^n), start = initial) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*e^{%0.3e* %s^%0.3e} ~~~~~ italic(R^2) == %0.2f", yname.formula, b, d, xname.formula, e, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black", family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/AM_analysis.R
#' Analysis: Brain-Cousens #' #' The 'BC.4' and 'BC.5' logistical models provide Brain-Cousens' modified logistical models to describe u-shaped hormesis. This model was extracted from the 'drc' package. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar Number of model parameters (\emph{default} is BC.4) #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position Legend position (\emph{default} is "top") #' @param r2 Coefficient of determination of the mean or all values (\emph{default} is all) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point Defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize Shape size #' @param linesize Line size #' @param linetype line type #' @param pointshape Format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The model function for the Brain-Cousens model (Brain and Cousens, 1989) is #' \deqn{y = c + \frac{d-c+fx}{1+\exp(b(\log(x)-\log(e)))}} #' and it is a five-parameter model, obtained by extending the four-parameter log-logistic model (LL.4 to take into account inverse u-shaped hormesis effects. #' Fixing the lower limit at 0 yields the four-parameter model #' \deqn{y = 0 + \frac{d-0+fx}{1+\exp(b(\log(x)-\log(e)))}} #' used by van Ewijk and Hoekstra (1993). #' @export #' @import ggplot2 #' @import drc #' @importFrom stats coef #' @importFrom stats sd #' @importFrom stats lm #' @importFrom stats cor #' @importFrom stats predict #' @importFrom stats fitted #' @importFrom stats AIC #' @importFrom stats BIC #' @importFrom stats glm #' @importFrom stats loess #' @importFrom stats nls #' @importFrom stats deviance #' @importFrom stats cov2cor #' @importFrom stats model.matrix #' @importFrom stats coefficients #' @importFrom stats vcov #' #' @author Model imported from the drc package (Ritz et al., 2016) #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Ritz, C.; Strebig, J.C. and Ritz, M.C. Package ‘drc’. Creative Commons: Mountain View, CA, USA, 2016. #' @seealso \link{LL}, \link{CD},\link{GP} #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' BC(trat,resp) BC=function(trat, resp, npar="BC.4", sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, error="SE", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd if(npar=="BC.4"){mod=drm(resp~trat,fct=BC.4()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3] f=coef$coefficients[,1][4] e=log(e)} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round) f=round(coef$coefficients[,1][4],round) e=log(e)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac(%0.3e %s %0.3e*%s, 1+e^{%0.3e*(log(%s) %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, d, ifelse(f >= 0, "+", "-"), abs(f), xname.formula, b, xname.formula, ifelse(e <= 0, "+", "-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) } if(npar=="BC.5"){mod=drm(resp~trat,fct=BC.5()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] f=coef$coefficients[,1][5] e=log(e) dc=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) f=round(coef$coefficients[,1][5],round) e=log(e) dc=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %0.3e + frac(%0.3e %s %0.3e*%s, 1+e^{%0.3e*(log(%s) %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, c, dc, ifelse(f >= 0, "+", "-"), abs(f), xname.formula, b, xname.formula, ifelse(e <= 0, "+", "-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+ geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd),size=linesize, width=width.bar)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(ic==TRUE){ pred=data.frame(x=xp, y=predict(mod,interval = "confidence",newdata = data.frame(trat=xp))) preditosic=data.frame(x=c(pred$x,pred$x[length(pred$x):1]), y=c(pred$y.Lower,pred$y.Upper[length(pred$x):1])) graph=graph+geom_polygon(data=preditosic,aes(x=x,y),fill=fill.ic,alpha=alpha.ic)} graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black", family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1), type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/BC_analysis.R
#' Analysis: Biexponential #' #' This function performs biexponential regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position Legend position (\emph{default} is "top") #' @param r2 Coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point Defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize Shape size #' @param linesize Line size #' @param linetype line type #' @param pointshape Format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The biexponential model is defined by: #' \deqn{y = A1 \times e^{-e^{lrc1 \cdot x}} + A2 \times e^{-e^{lrc2 \cdot x}}} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @export #' @seealso \link{asymptotic_neg} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' biexponential(time,WL) biexponential=function(trat, resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) model <- nls(resp~SSbiexp(trat,A1,lrc1,A2,lrc2)) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=exp(coef$coefficients[,1][2]) d=coef$coefficients[,1][3] e=exp(coef$coefficients[,1][4])} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(exp(coef$coefficients[,1][2]),round) d=round(coef$coefficients[,1][3],round) e=round(exp(coef$coefficients[,1][4]),round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 <- nls(ymean ~ SSbiexp(xmean,A1,lrc1,A2,lrc2)) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*e^{%0.3e*%s} %s %0.3e*e^{%0.3e*%s} ~~~~~ italic(R^2) == %0.2f", yname.formula, b, c, xname.formula, ifelse(d >= 0, "+", "-"), abs(d), e, xname.formula, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black", family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/BIEXP_analysis.R
#' Analysis: Cedergreen-Ritz-Streibig #' #' The 'CRS.4' and 'CRS.5' logistical models provide Brain-Cousens modified logistical models to describe u-shaped hormesis. This model was extracted from the 'drc' package. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar Number of model parameters #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The four-parameter model is given by the expression: #' #' \deqn{y = 0 + \frac{d-0+f \exp(-1/x)}{1+\exp(b(\log(x)-\log(e)))}} #' #' while the five-parameter is: #' #' \deqn{y = c + \frac{d-c+f \exp(-1/x)}{1+\exp(b(\log(x)-\log(e)))}} #' @seealso \link{LL}, \link{BC}, \link{GP} #' @export #' @author Model imported from the drc package (Ritz et al., 2016) #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Ritz, C.; Strebig, J.C.; Ritz, M.C. Package 'drc'. Creative Commons: Mountain View, CA, USA, 2016. #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' CD(trat,resp) CD=function(trat, resp, npar="CRS.4", sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") requireNamespace("drc") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd if(npar=="CRS.4"){mod=drm(resp~trat,fct=CRS.4a()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3] f=coef$coefficients[,1][4] e=log(e)} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round) f=round(coef$coefficients[,1][4],round) e=log(e)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac(%0.3e %s %0.3e*e^{frac(-1,%s)}, 1+e^{%0.3e*(log(%s) %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, d, ifelse(f >= 0, "+", "-"), abs(f), xname.formula, b, xname.formula, ifelse(e <= 0, "+", "-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) } if(npar=="CRS.5"){mod=drm(resp~trat,fct=CRS.5a()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] f=coef$coefficients[,1][5] e=log(e) dc=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) f=round(coef$coefficients[,1][5],round) e=log(e) dc=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %0.3e + frac(%0.3e %s %0.3e*e^{frac(-1,%s)}, 1+e^{%0.3e*(log(%s) %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, c, dc, ifelse(f >= 0, "+", "-"), abs(f), xname.formula, b, xname.formula, ifelse(e <= 0, "+", "-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+ geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd),size=linesize, width=width.bar)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(ic==TRUE){ pred=data.frame(x=xp, y=predict(mod,interval = "confidence",newdata = data.frame(trat=xp))) preditosic=data.frame(x=c(pred$x,pred$x[length(pred$x):1]), y=c(pred$y.Lower,pred$y.Upper[length(pred$x):1])) graph=graph+geom_polygon(data=preditosic,aes(x=x,y),fill=fill.ic,alpha=alpha.ic)} graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/CD_analysis.R
#' Analysis: Interval of confidence #' #' @description Interval of confidence in model regression #' @param model Object analysis #' @author Gabriel Danilo Shimizu #' @return Return in the interval of confidence #' @importFrom stats confint #' @export #' @examples #' data("granada") #' attach(granada) #' a=LM(time, WL) #' interval.confidence(a) interval.confidence=function(model){ modelo=model[[3]]$plot$model confint(modelo)}
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/IC_analysis.R
#' Analysis: Log-logistic #' #' Logistic models with three (LL.3), four (LL.4) or five (LL.5) continuous data parameters. This model was extracted from the drc package. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar Number of model parameters #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The three-parameter log-logistic function with lower limit 0 is #' \deqn{y = 0 + \frac{d}{1+\exp(b(\log(x)-\log(e)))}} #' The four-parameter log-logistic function is given by the expression #' \deqn{y = c + \frac{d-c}{1+\exp(b(\log(x)-\log(e)))}} #' The function is symmetric about the inflection point (e). #' @author Model imported from the drc package (Ritz et al., 2016) #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Ritz, C.; Strebig, J.C.; Ritz, M.C. Package ‘drc’. Creative Commons: Mountain View, CA, USA, 2016. #' @export #' #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' LL(trat,resp) LL=function(trat, resp, npar="LL.3", sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("drc") requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) if(npar=="LL.3"){mod=drm(resp~trat,fct=LL.3()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3] e=log(e)} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round) e=round(log(e),round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac(%0.3e, 1+e^{%0.3e*(log(%s) %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, d, b, xname.formula, ifelse(e <= 0, "+", "-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) } if(npar=="LL.5"){mod=drm(resp~trat,fct=LL.5()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] f=coef$coefficients[,1][5] e=log(e) dc=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) f=round(coef$coefficients[,1][5],round) e=round(log(e),round) dc=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %0.3e + frac(%0.3e, 1+e^(%0.3e*(log(%s) %s %0.3e))^%0.3e) ~~~~~ italic(R^2) == %0.2f", yname.formula, c, dc, b, xname.formula, ifelse(e <= 0, "+", "-"), abs(e), f, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} if(npar=="LL.4"){mod=drm(resp~trat,fct=LL.4()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] e=log(e) dc=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) e=round(log(e),round) dc=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~y == %0.3e + frac(%0.3e, 1+e^{%0.3e*(log(x) %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", c, dc, b, ifelse(e <= 0, "+", "-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(ic==TRUE){ pred=data.frame(x=xp, y=predict(mod,interval = "confidence",newdata = data.frame(trat=xp))) preditosic=data.frame(x=c(pred$x,pred$x[length(pred$x):1]), y=c(pred$y.Lower,pred$y.Upper[length(pred$x):1])) graph=graph+geom_polygon(data=preditosic,aes(x=x,y),fill=fill.ic,alpha=alpha.ic)} graph=graph+ theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family=fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(temp=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LL_analysis.R
#' Analysis: Cubic without beta2 #' #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description Degree 3 polynomial model without the beta 2 coefficient. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @details #' Degree 3 polynomial model without the beta 2 coefficient is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x + \beta_3\cdot x^{3}} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @keywords regression linear #' @export #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' LM13(time, WL) LM13=function(trat, resp, sample.curve=1000, ylab="Dependent", error="SE", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean) media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} dose=tapply(trat, trat, mean) moda=lm(resp~trat+I(trat^3)) mods=summary(moda)$coefficients modm=lm(media~dose+I(dose^3)) if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} if(r2=="all"){r2=round(summary(moda)$r.squared,2)} coef1=coef(moda)[1] coef2=coef(moda)[2] coef3=coef(moda)[3] s1 = s = sprintf("~~~%s == %e %s %e*%s %s %e*%s^3 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s1=paste(s1,"~\"",comment,"\"")} data1=data.frame(trat=unique(trat), resp=media, media=media, desvio) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(moda,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y predesp=predict(moda) predobs=resp if(point=="mean"){ graph=ggplot(data1,aes(x=trat,y=media)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=media-desvio, ymax=media+desvio), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} grafico=graph+theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = s1))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){grafico=grafico+scale_x_log10()} models=mods model=moda r2=summary(modm)$r.squared aic=AIC(moda) bic=BIC(moda) vif.test=function (mod){ if (any(is.na(coef(mod)))) stop("there are aliased coefficients in the model") v <- vcov(mod) assign <- attr(model.matrix(mod), "assign") if (names(coefficients(mod)[1]) == "(Intercept)") { v <- v[-1, -1] assign <- assign[-1]} else warning("No intercept: vifs may not be sensible.") terms <- labels(terms(mod)) n.terms <- length(terms) if (n.terms < 2) stop("model contains fewer than 2 terms") R <- cov2cor(v) detR <- det(R) result <- matrix(0, n.terms, 3) rownames(result) <- terms colnames(result) <- c("GVIF", "Df", "GVIF^(1/(2*Df))") for (term in 1:n.terms) { subs <- which(assign == term) result[term, 1] <- det(as.matrix(R[subs, subs])) * det(as.matrix(R[-subs, -subs]))/detR result[term, 2] <- length(subs)} if (all(result[, 2] == 1)) result <- result[, 1] else result[, 3] <- result[, 1]^(1/(2 * result[, 2])) result} vif=vif.test(moda) predesp=predict(moda) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(moda,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] cat("\n") graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=models, "values"=graphs, "plot"=grafico, "VIF"=vif) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LM13_analysis.R
#' Analysis: Cubic inverse without beta2 #' #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description Degree 3 polynomial inverse model without the beta 2 coefficient. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @details #' Inverse degree 3 polynomial model without the beta 2 coefficient is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x + \beta_3\cdot x^{1/3}} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @keywords regression linear #' @export #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' LM13i(time, WL) LM13i=function(trat, resp, sample.curve=1000, ylab="Dependent", error="SE", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean) media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} dose=tapply(trat, trat, mean) moda=lm(resp~trat+I(trat^(1/3))) mods=summary(moda)$coefficients modm=lm(media~dose+I(dose^(1/3))) if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} if(r2=="all"){r2=round(summary(moda)$r.squared,2)} coef1=coef(moda)[1] coef2=coef(moda)[2] coef3=coef(moda)[3] s1 = s = sprintf("~~~%s == %e %s %e*%s %s %e*%s^{1/3} ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s1=paste(s1,"~\"",comment,"\"")} data1=data.frame(trat=unique(trat), resp=media, media=media, desvio) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(moda,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y predesp=predict(moda) predobs=resp if(point=="mean"){ graph=ggplot(data1,aes(x=trat,y=media)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=media-desvio, ymax=media+desvio), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} grafico=graph+theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = s1))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){grafico=grafico+scale_x_log10()} models=mods model=moda r2=summary(modm)$r.squared aic=AIC(moda) bic=BIC(moda) vif.test=function (mod){ if (any(is.na(coef(mod)))) stop("there are aliased coefficients in the model") v <- vcov(mod) assign <- attr(model.matrix(mod), "assign") if (names(coefficients(mod)[1]) == "(Intercept)") { v <- v[-1, -1] assign <- assign[-1]} else warning("No intercept: vifs may not be sensible.") terms <- labels(terms(mod)) n.terms <- length(terms) if (n.terms < 2) stop("model contains fewer than 2 terms") R <- cov2cor(v) detR <- det(R) result <- matrix(0, n.terms, 3) rownames(result) <- terms colnames(result) <- c("GVIF", "Df", "GVIF^(1/(2*Df))") for (term in 1:n.terms) { subs <- which(assign == term) result[term, 1] <- det(as.matrix(R[subs, subs])) * det(as.matrix(R[-subs, -subs]))/detR result[term, 2] <- length(subs)} if (all(result[, 2] == 1)) result <- result[, 1] else result[, 3] <- result[, 1]^(1/(2 * result[, 2])) result} vif=vif.test(moda) predesp=predict(moda) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(moda,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] cat("\n") graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=models, "values"=graphs, "plot"=grafico, "VIF"=vif) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LM13i_analysis.R
#' Analysis: Cubic without beta1 #' #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description Degree 3 polynomial model without the beta 1 coefficient. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @details #' Degree 3 polynomial model without the beta 2 coefficient is defined by: #' \deqn{y = \beta_0 + \beta_2\cdot x^2 + \beta_3\cdot x^{3}} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @keywords regression linear #' @export #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' LM23(time, WL) LM23=function(trat, resp, sample.curve=1000, ylab="Dependent", error="SE", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean) media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} dose=tapply(trat, trat, mean) moda=lm(resp~I(trat^2)+I(trat^3)) mods=summary(moda)$coefficients modm=lm(media~I(dose^2)+I(dose^3)) if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} if(r2=="all"){r2=round(summary(moda)$r.squared,2)} coef1=coef(moda)[1] coef2=coef(moda)[2] coef3=coef(moda)[3] s1 = s = sprintf("~~~%s == %e %s %e*%s^2 %s %e*%s^3 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s1=paste(s1,"~\"",comment,"\"")} data1=data.frame(trat=unique(trat), resp=media, media=media, desvio) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(moda,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y predesp=predict(moda) predobs=resp if(point=="mean"){ graph=ggplot(data1,aes(x=trat,y=media)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=media-desvio, ymax=media+desvio), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} grafico=graph+theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = s1))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){grafico=grafico+scale_x_log10()} models=mods model=moda r2=summary(modm)$r.squared aic=AIC(moda) bic=BIC(moda) vif.test=function (mod){ if (any(is.na(coef(mod)))) stop("there are aliased coefficients in the model") v <- vcov(mod) assign <- attr(model.matrix(mod), "assign") if (names(coefficients(mod)[1]) == "(Intercept)") { v <- v[-1, -1] assign <- assign[-1]} else warning("No intercept: vifs may not be sensible.") terms <- labels(terms(mod)) n.terms <- length(terms) if (n.terms < 2) stop("model contains fewer than 2 terms") R <- cov2cor(v) detR <- det(R) result <- matrix(0, n.terms, 3) rownames(result) <- terms colnames(result) <- c("GVIF", "Df", "GVIF^(1/(2*Df))") for (term in 1:n.terms) { subs <- which(assign == term) result[term, 1] <- det(as.matrix(R[subs, subs])) * det(as.matrix(R[-subs, -subs]))/detR result[term, 2] <- length(subs)} if (all(result[, 2] == 1)) result <- result[, 1] else result[, 3] <- result[, 1]^(1/(2 * result[, 2])) result} vif=vif.test(moda) predesp=predict(moda) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(moda,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] cat("\n") graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=models, "values"=graphs, "plot"=grafico, "VIF"=vif) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LM23_analysis.R
#' Analysis: Cubic inverse without beta1 #' #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description Degree 3 polynomial inverse model without the beta 1 coefficient. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @details #' Inverse degree 3 polynomial model without the beta 1 coefficient is defined by: #' \deqn{y = \beta_0 + \beta_2\cdot x^{1/2} + \beta_3\cdot x^{1/3}} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @keywords regression linear #' @export #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' LM23i(time, WL) LM23i=function(trat, resp, sample.curve=1000, ylab="Dependent", error="SE", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean) media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} dose=tapply(trat, trat, mean) moda=lm(resp~I(trat^(1/2))+I(trat^(1/3))) mods=summary(moda)$coefficients modm=lm(media~I(dose^(1/2))+I(dose^(1/3))) if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} if(r2=="all"){r2=round(summary(moda)$r.squared,2)} coef1=coef(moda)[1] coef2=coef(moda)[2] coef3=coef(moda)[3] s1 = s = sprintf("~~~%s == %e %s %e*%s^{1/2} %s %e*%s^{1/3} ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s1=paste(s1,"~\"",comment,"\"")} data1=data.frame(trat=unique(trat), media=media, resp=media, desvio) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(moda,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y predesp=predict(moda) predobs=resp if(point=="mean"){ graph=ggplot(data1,aes(x=trat,y=media)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=media-desvio, ymax=media+desvio), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} grafico=graph+theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = s1))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){grafico=grafico+scale_x_log10()} models=mods model=moda r2=summary(modm)$r.squared aic=AIC(moda) bic=BIC(moda) vif.test=function (mod){ if (any(is.na(coef(mod)))) stop("there are aliased coefficients in the model") v <- vcov(mod) assign <- attr(model.matrix(mod), "assign") if (names(coefficients(mod)[1]) == "(Intercept)") { v <- v[-1, -1] assign <- assign[-1]} else warning("No intercept: vifs may not be sensible.") terms <- labels(terms(mod)) n.terms <- length(terms) if (n.terms < 2) stop("model contains fewer than 2 terms") R <- cov2cor(v) detR <- det(R) result <- matrix(0, n.terms, 3) rownames(result) <- terms colnames(result) <- c("GVIF", "Df", "GVIF^(1/(2*Df))") for (term in 1:n.terms) { subs <- which(assign == term) result[term, 1] <- det(as.matrix(R[subs, subs])) * det(as.matrix(R[-subs, -subs]))/detR result[term, 2] <- length(subs)} if (all(result[, 2] == 1)) result <- result[, 1] else result[, 3] <- result[, 1]^(1/(2 * result[, 2])) result} vif=vif.test(moda) predesp=predict(moda) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(moda,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] cat("\n") graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=models, "values"=graphs, "plot"=grafico, "VIF"=vif) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LM23i_analysis.R
#' Analysis: Cubic without beta1, with inverse beta3 #' #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description Degree 3 polynomial model without the beta 1 coefficient, with inverse beta3. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @details #' Inverse degree 3 polynomial model without the beta 2 coefficient is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x^2 + \beta_3\cdot x^{1/3}} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @keywords regression linear #' @export #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' LM2i3(time, WL) LM2i3=function(trat, resp, sample.curve=1000, ylab="Dependent", error="SE", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean) media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} dose=tapply(trat, trat, mean) moda=lm(resp~I(trat^2)+I(trat^(1/3))) mods=summary(moda)$coefficients modm=lm(media~I(dose^2)+I(dose^(1/3))) if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} if(r2=="all"){r2=round(summary(moda)$r.squared,2)} coef1=coef(moda)[1] coef2=coef(moda)[2] coef3=coef(moda)[3] s1 = s = sprintf("~~~%s == %e %s %e*%s^{2} %s %e*%s^{1/3} ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s1=paste(s1,"~\"",comment,"\"")} data1=data.frame(trat=unique(trat), media=media, resp=media, desvio) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(moda,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y predesp=predict(moda) predobs=resp if(point=="mean"){ graph=ggplot(data1,aes(x=trat,y=media)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=media-desvio, ymax=media+desvio), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} grafico=graph+theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = s1))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){grafico=grafico+scale_x_log10()} models=mods model=moda r2=summary(modm)$r.squared aic=AIC(moda) bic=BIC(moda) vif=NA predesp=predict(moda) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(moda,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] cat("\n") graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=models, "values"=graphs, "plot"=grafico, "VIF"=vif) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LM2i3_analysis.R
#' Analysis: Linear, quadratic, quadratic inverse, cubic and quartic #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description Linear, quadratic, quadratic inverse, cubic and quartic regression. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param degree degree of the polynomial (0.5, 1, 2, 3 or 4) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @details #' The linear model is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x} #' The quadratic model is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x + \beta_2\cdot x^2} #' The quadratic inverse model is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x + \beta_2\cdot x^{0.5}} #' The cubic model is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x + \beta_2\cdot x^2 + \beta_3\cdot x^3} #' The quartic model is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x + \beta_2\cdot x^2 + \beta_3\cdot x^3+ \beta_4\cdot x^4} #' #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @keywords regression linear #' @export #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' LM(trat,resp, degree = 3) LM=function(trat, resp, degree=NA, sample.curve=1000, ylab="Dependent", xlab="Independent", error="SE", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, point="all", r2="all", theme=theme_classic(), legend.position="top", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(is.na(degree)==TRUE){degree=1} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean) mod=c() mod1=c() mod2=c() mod05=c() modm=c() mod1m=c() mod2m=c() mod05m=c() text1=c() text2=c() text3=c() text05=c() mods=c() mod1s=c() mod2s=c() mod05s=c() media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} vif.test=function (mod){ if (any(is.na(coef(mod)))) stop("there are aliased coefficients in the model") v <- vcov(mod) assign <- attr(model.matrix(mod), "assign") if (names(coefficients(mod)[1]) == "(Intercept)") { v <- v[-1, -1] assign <- assign[-1]} else warning("No intercept: vifs may not be sensible.") terms <- labels(terms(mod)) n.terms <- length(terms) if (n.terms < 2) stop("model contains fewer than 2 terms") R <- cov2cor(v) detR <- det(R) result <- matrix(0, n.terms, 3) rownames(result) <- terms colnames(result) <- c("GVIF", "Df", "GVIF^(1/(2*Df))") for (term in 1:n.terms) { subs <- which(assign == term) result[term, 1] <- det(as.matrix(R[subs, subs])) * det(as.matrix(R[-subs, -subs]))/detR result[term, 2] <- length(subs)} if (all(result[, 2] == 1)) result <- result[, 1] else result[, 3] <- result[, 1]^(1/(2 * result[, 2])) result} dose=tapply(trat, trat, mean) if(degree=="1"){moda=lm(resp~trat)} if(degree=="2"){mod1a=lm(resp~trat+I(trat^2))} if(degree=="3"){mod2a=lm(resp~trat+I(trat^2)+I(trat^3))} if(degree=="4"){mod3a=lm(resp~trat+I(trat^2)+I(trat^3)+I(trat^4))} if(degree=="0.5"){mod05a=lm(resp~trat+I(trat^0.5))} if(degree=="1"){mods=summary(moda)$coefficients} if(degree=="2"){mod1s=summary(mod1a)$coefficients} if(degree=="3"){mod2s=summary(mod2a)$coefficients} if(degree=="4"){mod3s=summary(mod3a)$coefficients} if(degree=="0.5"){mod05s=summary(mod05a)$coefficients} if(degree=="1"){modm=lm(media~dose)} if(degree=="2"){mod1m=lm(media~dose+I(dose^2))} if(degree=="3"){mod2m=lm(media~dose+I(dose^2)+I(dose^3))} if(degree=="4"){mod3m=lm(media~dose+I(dose^2)+I(dose^3)+I(dose^4))} if(degree=="0.5"){mod05m=lm(media~dose+I(dose^0.5))} if(r2=="mean"){ if(degree=="1"){r2=round(summary(modm)$r.squared,2)} if(degree=="2"){r2=round(summary(mod1m)$r.squared,2)} if(degree=="3"){r2=round(summary(mod2m)$r.squared,2)} if(degree=="4"){r2=round(summary(mod3m)$r.squared,2)} if(degree=="0.5"){r2=round(summary(mod05m)$r.squared,2)}} if(r2=="all"){ if(degree=="1"){r2=round(summary(moda)$r.squared,2)} if(degree=="2"){r2=round(summary(mod1a)$r.squared,2)} if(degree=="3"){r2=round(summary(mod2a)$r.squared,2)} if(degree=="4"){r2=round(summary(mod3a)$r.squared,2)} if(degree=="0.5"){r2=round(summary(mod05a)$r.squared,2)}} if(degree=="1"){ if(is.na(round)==TRUE){ coef1=coef(moda)[1] coef2=coef(moda)[2]} if(is.na(round)==FALSE){ coef1=round(coef(moda)[1],round) coef2=round(coef(moda)[2],round)} s1=s <- sprintf("~~~%s == %e %s %e* %s ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, r2) if(is.na(comment)==FALSE){s1=paste(s1,"~\"",comment,"\"")}} if(degree=="2"){ if(is.na(round)==TRUE){ coef1=coef(mod1a)[1] coef2=coef(mod1a)[2] coef3=coef(mod1a)[3]} if(is.na(round)==FALSE){ coef1=round(coef(mod1a)[1],round) coef2=round(coef(mod1a)[2],round) coef3=round(coef(mod1a)[3],round)} s2=s <- sprintf("~~~%s == %e %s %e * %s %s %e * %s^2 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s2=paste(s2,"~\"",comment,"\"")}} if(degree=="3"){ if(is.na(round)==TRUE){ coef1=coef(mod2a)[1] coef2=coef(mod2a)[2] coef3=coef(mod2a)[3] coef4=coef(mod2a)[4]} if(is.na(round)==FALSE){ coef1=round(coef(mod2a)[1],round) coef2=round(coef(mod2a)[2],round) coef3=round(coef(mod2a)[3],round) coef4=round(coef(mod2a)[4],round)} s3=s <- sprintf("~~~%s == %e %s %e * %s %s %e * %s^2 %s %0.e * %s^3 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, ifelse(coef4 >= 0, "+", "-"), abs(coef4), xname.formula, r2) if(is.na(comment)==FALSE){s3=paste(s3,"~\"",comment,"\"")}} if(degree=="4"){ if(is.na(round)==TRUE){ coef1=coef(mod3a)[1] coef2=coef(mod3a)[2] coef3=coef(mod3a)[3] coef4=coef(mod3a)[4] coef5=coef(mod3a)[5]} if(is.na(round)==FALSE){ coef1=round(coef(mod3a)[1],round) coef2=round(coef(mod3a)[2],round) coef3=round(coef(mod3a)[3],round) coef4=round(coef(mod3a)[4],round) coef5=round(coef(mod3a)[5],round)} s4=s <- sprintf("~~~%s == %e %s %e * %s %s %e * %s^2 %s %0.e * %s^3 %s %0.e * %s^4 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, ifelse(coef4 >= 0, "+", "-"), abs(coef4), xname.formula, ifelse(coef5 >= 0, "+", "-"), abs(coef5), xname.formula, r2) if(is.na(comment)==FALSE){s4=paste(s4,"~\"",comment,"\"")}} if(degree=="0.5"){ if(is.na(round)==TRUE){ coef1=coef(mod05a)[1] coef2=coef(mod05a)[2] coef3=coef(mod05a)[3]} if(is.na(round)==FALSE){ coef1=round(coef(mod05a)[1],round) coef2=round(coef(mod05a)[2],round) coef3=round(coef(mod05a)[3],round)} s05=s <- sprintf("~~~%s == %e %s %e * %s %s %e * %s^0.5 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s05=paste(s05,"~\"",comment,"\"")}} data1=data.frame(trat=as.numeric(names(media)), resp=media, desvio) if(point=="mean"){ grafico=ggplot(data1,aes(x=trat,y=resp))+ geom_point(aes(fill=as.factor(rep(1,length(resp)))),na.rm=TRUE, size=pointsize,color="black",shape=pointshape)} if(point=="mean" & error!="FALSE"){ grafico=ggplot(data1,aes(x=trat,y=resp))+ geom_errorbar(aes(ymin=resp-desvio, ymax=resp+desvio), width=width.bar, size=linesize)+ geom_point(aes(fill=as.factor(rep(1,length(resp)))),na.rm=TRUE, size=pointsize,color="black",shape=pointshape)} if(point=="all"){ grafico=ggplot(data.frame(trat,resp),aes(x=trat,y=resp))+ geom_point(aes(fill=as.factor(rep(1,length(resp)))),size=pointsize, shape=pointshape,color="black")} grafico=grafico+ theme+ylab(ylab)+xlab(xlab) if(degree=="1"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic, na.rm=TRUE, formula = y~x,size=linesize,color=colorline,lty=linetype)} if(degree=="2"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic,na.rm=TRUE, formula = y~x+I(x^2),size=linesize,color=colorline,lty=linetype)} if(degree=="3"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic,na.rm=TRUE, formula = y~x+I(x^2)+I(x^3),size=linesize,color=colorline,lty=linetype)} if(degree=="4"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic,na.rm=TRUE, formula = y~x+I(x^2)+I(x^3)+I(x^4),size=linesize,color=colorline,lty=linetype)} if(degree=="0.5"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic,na.rm=TRUE, formula = y~x+I(x^0.5),size=linesize,color=colorline,lty=linetype)} if(degree=="1"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s1)),name="")} if(degree=="2"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s2)),name="")} if(degree=="3"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s3)),name="")} if(degree=="4"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s4)),name="")} if(degree=="0.5"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s05)),name="")} grafico=grafico+ theme(text = element_text(size=textsize,color="black",family = fontfamily), axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text=element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0) if(scale=="log"){grafico=grafico+scale_x_log10()} if(degree=="1"){moda=lm(resp~trat)} if(degree=="2"){mod1a=lm(resp~trat+I(trat^2))} if(degree=="3"){mod2a=lm(resp~trat+I(trat^2)+I(trat^3))} if(degree=="4"){mod3a=lm(resp~trat+I(trat^2)+I(trat^3)+I(trat^4))} if(degree=="0.5"){mod05a=lm(resp~trat+I(trat^0.5))} if(degree=="1"){ models=mods model=moda # r2=summary(modm)$r.squared aic=AIC(moda) bic=BIC(moda) vif=NA predesp=predict(moda) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(moda,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] } if(degree=="2"){ models=mod1s model=mod1a # r2=summary(mod1m)$r.squared aic=AIC(mod1a) bic=BIC(mod1a) # vif=car::vif(mod1a) vif=vif.test(mod1a) predesp=predict(mod1a) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod1a,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] } if(degree=="3"){ models=mod2s model=mod2a # r2=summary(mod2m)$r.squared aic=AIC(mod2a) bic=BIC(mod2a) # vif=car::vif(mod2a) vif=vif.test(mod2a) predesp=predict(mod2a) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod2a,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)]} if(degree=="4"){ models=mod3s model=mod3a # r2=summary(mod3m)$r.squared aic=AIC(mod3a) bic=BIC(mod3a) # vif=car::vif(mod3a) vif=vif.test(mod3a) predesp=predict(mod3a) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod3a,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)]} if(degree=="0.5"){ models=mod05s model=mod05a # r2=summary(mod05m)$r.squared aic=AIC(mod05a) bic=BIC(mod05a) # vif=car::vif(mod05a) vif=vif.test(mod05a) predesp=predict(mod05a) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod05a,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] } cat("\n") graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=models, "values"=graphs, "plot"=grafico, "VIF"=vif) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LM_analysis.R
#' Analysis: Linear, quadratic, quadratic inverse, cubic and quartic without intercept #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description Linear, quadratic, quadratic inverse, cubic and quartic regression. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param degree degree of the polynomial (0.5, 1, 2, 3 or 4) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @details #' The linear model is defined by: #' \deqn{y = \beta_1\cdot x} #' The quadratic model is defined by: #' \deqn{y = \beta_1\cdot x + \beta_2\cdot x^2} #' The quadratic inverse model is defined by: #' \deqn{y = \beta_1\cdot x + \beta_2\cdot x^{0.5}} #' The cubic model is defined by: #' \deqn{y = \beta_1\cdot x + \beta_2\cdot x^2 + \beta_3\cdot x^3} #' The quartic model is defined by: #' \deqn{y = \beta_1\cdot x + \beta_2\cdot x^2 + \beta_3\cdot x^3+ \beta_4\cdot x^4} #' #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @keywords regression linear #' @export #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' LM_i(trat,resp, degree = 3) LM_i=function(trat, resp, sample.curve=1000, ylab = "Dependent", error = "SE", ic = FALSE, fill.ic = "gray70", alpha.ic = 0.5, xlab = "Independent", degree = NA, theme = theme_classic(), legend.position = "top", point = "all", r2="all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, xname.formula="x", yname.formula="y", comment = NA, fontfamily="sans") { requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(is.na(degree)==TRUE){degree=1} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean) mod=c() mod1=c() mod2=c() mod05=c() modm=c() mod1m=c() mod2m=c() mod05m=c() text1=c() text2=c() text3=c() text05=c() mods=c() mod1s=c() mod2s=c() mod05s=c() media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} dose=tapply(trat, trat, mean) moda=lm(resp~trat-1) mod1a=lm(resp~trat+I(trat^2)-1) mod2a=lm(resp~trat+I(trat^2)+I(trat^3)-1) mod3a=lm(resp~trat+I(trat^2)+I(trat^3)+I(trat^4)-1) mod05a=lm(resp~trat+I(trat^0.5)-1) mods=summary(moda)$coefficients mod1s=summary(mod1a)$coefficients mod2s=summary(mod2a)$coefficients mod3s=summary(mod3a)$coefficients mod05s=summary(mod05a)$coefficients modm=lm(media~dose-1) mod1m=lm(media~dose+I(dose^2)-1) mod2m=lm(media~dose+I(dose^2)+I(dose^3)-1) mod3m=lm(media~dose+I(dose^2)+I(dose^3)+I(dose^4)-1) mod05m=lm(media~dose+I(dose^0.5)-1) if(r2=="mean"){ if(degree=="1"){r2=round(summary(modm)$r.squared,2)} if(degree=="2"){r2=round(summary(mod1m)$r.squared,2)} if(degree=="3"){r2=round(summary(mod2m)$r.squared,2)} if(degree=="4"){r2=round(summary(mod3m)$r.squared,2)} if(degree=="0.5"){r2=round(summary(mod05m)$r.squared,2)}} if(r2=="all"){ if(degree=="1"){r2=round(summary(moda)$r.squared,2)} if(degree=="2"){r2=round(summary(mod1a)$r.squared,2)} if(degree=="3"){r2=round(summary(mod2a)$r.squared,2)} if(degree=="4"){r2=round(summary(mod3a)$r.squared,2)} if(degree=="0.5"){r2=round(summary(mod05a)$r.squared,2)}} if(degree=="1"){ if(is.na(round)==TRUE){coef1=coef(moda)[1]} if(is.na(round)==FALSE){coef1=round(coef(moda)[1],round)} s1= s = sprintf("~~~%s == %e*%s ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, xname.formula, r2) if(is.na(comment)==FALSE){s1=paste(s1,"~\"",comment,"\"")}} if(degree=="2"){ if(is.na(round)==TRUE){ coef1=coef(mod1a)[1] coef2=coef(mod1a)[2]} if(is.na(round)==FALSE){ coef1=round(coef(mod1a)[1],round) coef2=round(coef(mod1a)[2],round)} s2 = s = sprintf("~~~%s == %e * %s %s %e * %s^2 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, xname.formula, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, r2) if(is.na(comment)==FALSE){s2=paste(s2,"~\"",comment,"\"")}} if(degree=="3"){ if(is.na(round)==TRUE){ coef1=coef(mod2a)[1] coef2=coef(mod2a)[2] coef3=coef(mod2a)[3]} if(is.na(round)==FALSE){ coef1=round(coef(mod2a)[1],round) coef2=round(coef(mod2a)[2],round) coef3=round(coef(mod2a)[3],round)} s3 = s = sprintf("~~~%s == %e * %s %s %e * %s^2 %s %0.e * %s^3 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, xname.formula, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, r2) if(is.na(comment)==FALSE){s3=paste(s3,"~\"",comment,"\"")}} if(degree=="4"){ if(is.na(round)==TRUE){ coef1=coef(mod3a)[1] coef2=coef(mod3a)[2] coef3=coef(mod3a)[3] coef4=coef(mod3a)[4]} if(is.na(round)==FALSE){ coef1=round(coef(mod3a)[1],round) coef2=round(coef(mod3a)[2],round) coef3=round(coef(mod3a)[3],round) coef4=round(coef(mod3a)[4],round)} s4 = s = sprintf("~~~%s == %e * %s %s %e * %s^2 %s %0.e * %s^3 %s %0.e * %s^4 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, xname.formula, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, ifelse(coef4 >= 0, "+", "-"), abs(coef4), xname.formula, r2) if(is.na(comment)==FALSE){s4=paste(s4,"~\"",comment,"\"")}} if(degree=="0.5"){ if(is.na(round)==TRUE){ coef1=coef(mod05a)[1] coef2=coef(mod05a)[2]} if(is.na(round)==FALSE){ coef1=round(coef(mod05a)[1],round) coef2=round(coef(mod05a)[2],round)} s05 = s = sprintf("~~~%s == %e * %s %s %e * %s^0.5 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, xname.formula, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, r2) if(is.na(comment)==FALSE){s05=paste(s05,"~\"",comment,"\"")}} data1=data.frame(trat,resp) data1=data.frame(trat=unique(trat), resp=media, desvio) if(point=="mean"){ grafico=ggplot(data1,aes(x=trat,y=resp))+ geom_point(aes(fill=as.factor(rep(1,length(resp)))),na.rm=TRUE, size=pointsize,color="black",shape=pointshape) if(error!="FALSE"){grafico=grafico+ geom_errorbar(aes(ymin=resp-desvio, ymax=resp+desvio), width=width.bar, size=linesize)}} if(point=="all"){ grafico=ggplot(data.frame(trat,resp),aes(x=trat,y=resp))+ geom_point(aes(fill=as.factor(rep(1,length(resp)))),size=pointsize, shape=pointshape,color="black")} grafico=grafico+ theme+ylab(ylab)+xlab(xlab) if(degree=="1"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic, na.rm=TRUE, formula = y~x-1,size=linesize,color=colorline,lty=linetype)} if(degree=="2"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic, na.rm=TRUE, formula = y~x+I(x^2)-1,size=linesize,color=colorline,lty=linetype)} if(degree=="3"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic, na.rm=TRUE, formula = y~x+I(x^2)+I(x^3)-1,size=linesize,color=colorline,lty=linetype)} if(degree=="4"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic, na.rm=TRUE, formula = y~x+I(x^2)+I(x^3)+I(x^4)-1,size=linesize,color=colorline,lty=linetype)} if(degree=="0.5"){grafico=grafico+geom_smooth(method = "lm",se=ic, fill=fill.ic, alpha=alpha.ic, na.rm=TRUE, formula = y~x+I(x^0.5)-1,size=linesize,color=colorline,lty=linetype)} if(degree=="1"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s1)),name="")} if(degree=="2"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s2)),name="")} if(degree=="3"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s3)),name="")} if(degree=="4"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s4)),name="")} if(degree=="0.5"){grafico=grafico+ scale_fill_manual(values=fillshape,label=c(parse(text=s05)),name="")} grafico=grafico+ theme(text = element_text(size=textsize,color="black",family = fontfamily), axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text=element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0) if(scale=="log"){grafico=grafico+scale_x_log10()} moda=lm(resp~trat-1) mod1a=lm(resp~trat+I(trat^2)-1) mod2a=lm(resp~trat+I(trat^2)+I(trat^3)-1) mod3a=lm(resp~trat+I(trat^2)+I(trat^3)+I(trat^4)-1) mod05a=lm(resp~trat+I(trat^0.5)-1) vif.test=function (mod){ if (any(is.na(coef(mod)))) stop("there are aliased coefficients in the model") v <- vcov(mod) assign <- attr(model.matrix(mod), "assign") if (names(coefficients(mod)[1]) == "(Intercept)") { v <- v[-1, -1] assign <- assign[-1]} else warning("No intercept: vifs may not be sensible.") terms <- labels(terms(mod)) n.terms <- length(terms) if (n.terms < 2) stop("model contains fewer than 2 terms") R <- cov2cor(v) detR <- det(R) result <- matrix(0, n.terms, 3) rownames(result) <- terms colnames(result) <- c("GVIF", "Df", "GVIF^(1/(2*Df))") for (term in 1:n.terms) { subs <- which(assign == term) result[term, 1] <- det(as.matrix(R[subs, subs])) * det(as.matrix(R[-subs, -subs]))/detR result[term, 2] <- length(subs)} if (all(result[, 2] == 1)) result <- result[, 1] else result[, 3] <- result[, 1]^(1/(2 * result[, 2])) result} if(degree=="1"){ model=models=mods r2=summary(modm)$r.squared aic=AIC(moda) bic=BIC(moda) vif=NA predesp=predict(moda) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(moda,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] } if(degree=="2"){ model=models=mod1s r2=summary(mod1m)$r.squared aic=AIC(mod1a) bic=BIC(mod1a) vif=vif.test(mod1a) predesp=predict(mod1a) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod1a,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] } if(degree=="3"){ model=models=mod2s r2=summary(mod2m)$r.squared aic=AIC(mod2a) bic=BIC(mod2a) vif=vif.test(mod2a) predesp=predict(mod2a) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod2a,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)]} if(degree=="4"){ model=models=mod3s r2=summary(mod3m)$r.squared aic=AIC(mod3a) bic=BIC(mod3a) vif=vif.test(mod3a) predesp=predict(mod3a) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod3a,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)]} if(degree=="0.5"){ model=models=mod05s r2=summary(mod05m)$r.squared aic=AIC(mod05a) bic=BIC(mod05a) vif=vif.test(mod05a) predesp=predict(mod05a) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod05a,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] } cat("\n") graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=models, "test"=graphs, "plot"=grafico, "VIF"=vif) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LM_i_analysis.R
#' Analysis: Linear-Plateau #' #' This function performs the linear-plateau regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); breakpoint and the graph using ggplot2 with the equation automatically. #' @export #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Chiu, G. S., R. Lockhart, and R. Routledge. 2006. Bent-cable regression theory and applications. Journal of the American Statistical Association 101:542-553. #' @references Toms, J. D., and M. L. Lesperance. 2003. Piecewise regression: a tool for identifying ecological thresholds. Ecology 84:2034-2041. #' @seealso \link{quadratic.plateau}, \link{linear.linear} #' @importFrom dplyr if_else #' @details #' The linear-plateau model is defined by: #' First curve: #' \deqn{y = \beta_0 + \beta_1 \times x (x < breakpoint)} #' #' Second curve: #' \deqn{y = \beta_0 + \beta_1 \times breakpoint (x > breakpoint)} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' linear.plateau(time,WL) linear.plateau=function(trat,resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} lp <- function(x, a, b, c) { if_else(condition = x < c, true = a + b * x, false = a + b * c) } data=data.frame(trat,resp) ini_fit <- lm(data = data, formula = resp ~ trat) ini_a <- ini_fit$coef[[1]] ini_b <- ini_fit$coef[[2]] ini_c <- mean(data$trat) lp_model <- nlsLM( formula = resp ~ lp(trat, a, b, c), data = data, start = list(a = ini_a, b = ini_c, c = ini_c)) model2=summary(lp_model) breakpoint=model2$coefficients[3,1] ybreakpoint=predict(lp_model,newdata = data.frame(trat=breakpoint)) m.ini <- mean(data$resp) nullfunct <- function(x, m) { m } null <- nls(resp~ nullfunct(trat, m), data = data, start = list(m = m.ini), trace = FALSE, nls.control(maxiter = 1000)) r2 <- nagelkerke(lp_model, null)$Pseudo.R.squared.for.model.vs.null[2] requireNamespace("drc") requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) r2=floor(r2*100)/100 if(is.na(round)==TRUE){ coef1=coef(model2)[1] coef2=coef(model2)[2] coef3=breakpoint} if(is.na(round)==FALSE){ coef1=round(coef(model2)[1],round) coef2=round(coef(model2)[2],round) coef3=round(breakpoint,round)} s <- sprintf("~~~%s == %e %s %e * %s ~(%s~'<'~%e) ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, xname.formula, coef3, r2) equation=s if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(lp_model) predobs=resp model=lp_model rmse=sqrt(mean((predesp-predobs)^2)) data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} xp=seq(min(trat),max(trat),length=sample.curve) yp=predict(lp_model,newdata=data.frame(trat=xp)) preditos=data.frame(x=xp,y=yp) temp1=xp result=yp x=xp y=yp graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} aic=AIC(lp_model) bic=BIC(lp_model) minimo=NA respmin=NA graphs=data.frame("Parameter"=c("Breakpoint", "Breakpoint response", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(breakpoint, ybreakpoint, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients segmented"=model2, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LNplt_analysis.R
#' Analysis: Logarithmic quadratic #' #' This function performs logarithmic quadratic regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is c(0.3,0.8)) #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The logarithmic model is defined by: #' \deqn{y = \beta_0 + \beta_1 ln(\cdot x) + \beta_2 ln(\cdot x)^2} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @export #' #' @examples #' library(AgroReg) #' resp=c(10,8,6.8,6,5,4.3,4.1,4.2,4.1) #' trat=seq(1,9,1) #' LOG2(trat,resp) LOG2=function(trat, resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("drc") requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) model <- lm(resp ~ log(trat)+I(log(trat)^2)) model1<- lm(ymean ~ log(xmean)+I(log(xmean)^2)) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=coef$r.squared} if(r2=="mean"){ coef1=summary(model1) r2=coef1$r.squared} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e %s %0.3e*ln(%s) %s %0.3e*ln(%s)^2 ~~~~~ italic(R^2) == %0.2f", yname.formula, d, ifelse(b<0,"-","+"), abs(b), xname.formula, ifelse(e<0,"-","+"), abs(e), xname.formula, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LOG2_analysis.R
#' Analysis: Logarithmic #' #' This function performs logarithmic regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is c(0.3,0.8)) #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The logarithmic model is defined by: #' \deqn{y = \beta_0 + \beta_1 ln(\cdot x)} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @export #' #' @examples #' library(AgroReg) #' resp=c(10,8,6.8,6,5,4.3,4.1,4.2,4.1) #' trat=seq(1,9,1) #' LOG(trat,resp) LOG=function(trat, resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("drc") requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) model <- lm(resp ~ log(trat)) model1<- lm(ymean ~ log(xmean)) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round)} if(r2=="all"){r2=coef$r.squared} if(r2=="mean"){ coef1=summary(model1) r2=coef1$r.squared} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e %s %0.3e*ln(%s) ~~~~~ italic(R^2) == %0.2f", yname.formula, d, ifelse(b<0,"-","+"), abs(b), xname.formula, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/LOG_analysis.R
#' Analysis: Michaelis-Menten #' #' This function performs regression analysis using the Michaelis-Menten model. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar Number of parameters (mm2 or mm3) #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @details #' The two-parameter Michaelis-Menten model is defined by: #' \deqn{y = \frac{Vm \times x}{k + x}} #' The three-parameter Michaelis-Menten model is defined by: #' \deqn{y = c + \frac{Vm \times x}{k + x}} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @export #' @author Gabriel Danilo Shimizu #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @examples #' data("granada") #' attach(granada) #' MM(time,WL) #' MM(time,WL,npar="mm3") #' @md MM=function(trat, resp, npar="mm2", sample.curve=1000, error="SE", ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", point="all", width.bar=NA, r2="all", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd if(npar=="mm2"){ mod=drm(resp~trat,fct=MM.2()) mod=nls(resp~((trat*Vm)/(k+trat)),start = list(Vm=coef(mod)[1], k=coef(mod)[2])) model=mod coef=summary(mod) if(is.na(round)==TRUE){ d=coef$coefficients[,1][1] e=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ d=round(coef$coefficients[,1][1],round) e=round(coef$coefficients[,1][2],round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac(%0.3e*%s, %0.3e + %s)~~~~~ italic(R^2) == %0.2f", yname.formula, d, xname.formula, e, xname.formula, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} mod=drm(resp~trat,fct=MM.2())} if(npar=="mm3"){ mod=drm(resp~trat,fct=MM.3()) mod=nls(resp~((trat*Vm)/(k+trat))+c,start = list(c=coef(mod)[1], Vm=coef(mod)[2], k=coef(mod)[3])) model=mod coef=summary(mod) if(is.na(round)==TRUE){ c=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ c=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s== %0.3e + frac(%0.3e*%s, %0.3e + %s) ~~~~~ italic(R^2) == %0.2f", yname.formula, c, d, xname.formula, e, xname.formula, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} mod=drm(resp~trat,fct=MM.3())} s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(ic==TRUE){ pred=data.frame(x=xp, y=predict(mod,interval = "confidence",newdata = data.frame(trat=xp))) preditosic=data.frame(x=c(pred$x,pred$x[length(pred$x):1]), y=c(pred$y.Lower,pred$y.Upper[length(pred$x):1])) graph=graph+geom_polygon(data=preditosic,aes(x=x,y),fill=fill.ic,alpha=alpha.ic)} graph=graph+theme+ geom_line(data=preditos,aes(x=x,y=y,color="black"), size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/MM_analysis.R
#' Analysis: Graph for not significant trend #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description Graph for non-significant trend. Can be used within the multicurve command #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param width.bar Bar width #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param legend.position legend position (\emph{default} is "top") #' @param legend.text legend text #' @param legend.add.mean Add average in legend #' @param legend.add.mean.name Add media name #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param textsize Font size #' @param pointsize shape size #' @param add.line Add line #' @param add.line.mean Add line mean #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param fontfamily Font family #' @return The function returns an exploratory graph of segments #' @keywords non-significant #' @export #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' Nreg(trat,resp) Nreg=function(trat, resp, ylab="Dependent", xlab="Independent", error="SE", theme=theme_classic(), legend.position="top", legend.text="not~significant", legend.add.mean=TRUE, legend.add.mean.name="hat(y)", width.bar=NA, point="all", textsize = 12, add.line=FALSE, add.line.mean=FALSE, linesize=0.8, linetype=1, pointsize = 4.5, pointshape = 21, fillshape = "gray", colorline = "black", fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") dados=data.frame(trat,resp) dose=tapply(trat, trat, mean) media=tapply(resp, trat, mean) if(error=="SE"){desvio=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){desvio=tapply(resp,trat,sd)} if(error=="FALSE"){desvio=0} data1=data.frame(trat,resp) data1=data.frame(trat=dose, resp=media, desvio) temp1=dose result=media s=legend.text if(legend.add.mean==TRUE){s=paste(legend.text,"~","(",legend.add.mean.name,"==",mean(media),")")} if(point=="mean"){ grafico=ggplot(data1,aes(x=trat,y=resp)) if(add.line==TRUE){grafico=grafico+geom_line(size=linesize)} if(add.line.mean==TRUE){grafico=grafico+geom_hline(yintercept = mean(resp,na.rm=TRUE),lty=2)} if(error!="FALSE"){grafico=grafico+ geom_errorbar(aes(ymin=resp-desvio,ymax=resp+desvio), width=width.bar, size=linesize)} grafico=grafico+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape) } if(point=="all"){ grafico=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) if(add.line==TRUE){grafico=grafico+stat_summary(geom="line",fun = "mean", size=linesize,color=colorline,lty=linetype)} if(add.line.mean==TRUE){grafico=grafico+geom_hline(yintercept = mean(resp,na.rm=TRUE),lty=2,color=colorline)} grafico=grafico+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(add.line.mean==TRUE){result=mean(media)} grafico=grafico+theme+ylab(ylab)+xlab(xlab)+ scale_color_manual(values=colorline,label=c(parse(text=s)),name="")+ theme(text = element_text(size=textsize,color="black"), axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text=element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0) graficos=list("values"="not significant", NA, "plot"=grafico) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/N_analysis.R
#' Analysis: Page #' #' This function performs exponential page regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param initial Starting estimates #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param comment Add text after equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param round round equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The exponential model is defined by: #' \deqn{y = e^{-k \cdot x^n}} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @export #' #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' PAGE(time,100-WL) PAGE=function(trat, resp, initial=NA, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) if(is.na(initial[1])==TRUE){ mod=lm(log(resp)~trat) k=coef(mod)[1] n=coef(mod)[2] initial=list(k=k,n=n)} model=nls(resp~exp(k*trat^n),start = initial) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1=nls(ymean~exp(k*xmean^n),start = initial) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==e^{%0.3e*%s^%0.3e} ~~~~~ italic(R^2) == %0.2f", yname.formula, b, xname.formula, d, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/PAGE_analysis.R
#' Analysis: Steinhart-Hart #' #' The Steinhart-Hart model. The Steinhart-Hart equation is a model used to explain the behavior of a semiconductor at different temperatures, however, Zhai et al. (2020) used this model to relate plant density and grain yield. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param initial Starting estimates #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position Legend position (\emph{default} is "top") #' @param r2 Coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point Defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize Shape size #' @param linesize Line size #' @param linetype line type #' @param pointshape Format point (default is 21) #' @param round round equation #' @param colorline Color lines #' @param fillshape Fill shape #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The model function for the Steinhart-Hart model is: #' \deqn{ y = \frac{1}{A+B \times ln(x)+C \times ln(x)^3}} #' @export #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Zhai, L., Li, H., Song, S., Zhai, L., Ming, B., Li, S., ... & Zhang, L. (2021). Intra-specific competition affects the density tolerance and grain yield of maize hybrids. Agronomy Journal, 113(1), 224-23. doi:10.1002/agj2.20438 #' @seealso \link{LL}, \link{CD},\link{GP} #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' SH(trat,resp) SH=function(trat, resp, initial=NA, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", error="SE", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd if(is.na(initial[1])==TRUE){ ix=1/max(resp) initial=list(A=ix,B=ix,C=ix)} mod=nls(resp~1/(A+B*log(trat)+C*log(trat)^3),start = initial) model=mod coef=summary(mod) if(is.na(round)==TRUE){ A=coef$coefficients[,1][1] B=coef$coefficients[,1][2] C=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ A=round(coef$coefficients[,1][1],round) B=round(coef$coefficients[,1][2],round) C=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1=nls(ymean~1/(A+B*log(xmean)+C*log(xmean)^3),start = initial) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac(1, %0.3e %s %0.3e*ln(%s) %s %0.3e*ln(%s)^3) ~~~~~ italic(R^2) == %0.2f", yname.formula, A, ifelse(B >= 0, "+", "-"), abs(B), xname.formula, ifelse(C >= 0, "+", "-"), C, xname.formula, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+ geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd),size=linesize, width=width.bar)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1), type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/SH_function.R
#' Analysis: Von Bertalanffy #' #' The Von Bertalanffy model. It's a kind of growth curve for a time series and takes its name from its creator, Ludwig von Bertalanffy. It is a special case of the generalized logistic function. The growth curve (biology) is used to model the average length from age in animals. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param initial Starting estimates #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position Legend position (\emph{default} is "top") #' @param r2 Coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point Defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize Shape size #' @param linesize Line size #' @param linetype line type #' @param pointshape Format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The model function for the von Bertalanffy model is: #' \deqn{ y = L(1-exp(-k(t-t0)))} #' @export #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @examples #' library(AgroReg) #' x=seq(1,20) #' y=c(0.10, 0.20, 0.30, 0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 0.91, #' 0.92, 0.94, 0.96, 0.98, 1.00, 1.00, 1.00, 1.00, 1.00, 1.00) #' VB(x,y) VB=function(trat, resp, initial=NA, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", error="SE", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd if(is.na(initial[1])==TRUE){ L=max(resp) k=1 t0=1 initial=list(L=L,k=k,t0=t0)} mod=nls(resp~L*(1-exp(-k*(trat-t0))),start = initial) model=mod coef=summary(mod) if(is.na(round)==TRUE){ L=coef$coefficients[,1][1] k=coef$coefficients[,1][2] t0=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ L=round(coef$coefficients[,1][1],round) k=round(coef$coefficients[,1][2],round) t0=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1=nls(ymean~L*(1-exp(-k*(xmean-t0))),start = initial) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*(1-e^{%s %0.3e*(%s %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, L, ifelse(k<0,"+","-"), abs(k), xname.formula, ifelse(t0<0,"+","-"), abs(t0), r2) xp=seq(min(trat),max(trat),length.out = 1000) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+ geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd),size=linesize, width=width.bar)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1), type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/VB_analysis.R
#' Analysis: Vega-Galvez #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description This function performs Vega-Galvez regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param legend.position legend position (\emph{default} is "top") #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param fontfamily Font family #' #' @details #' The Vega-Galvez model is defined by: #' \deqn{y = \beta_0 + \beta_1 (\sqrt{x})} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @references Sadeghi, E., Haghighi Asl, A., and Movagharnejad, K. (2019). Mathematical modelling of infrared-dried kiwifruit slices under natural and forced convection. Food science & nutrition, 7(11), 3589-3606. #' @export #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' VG(trat,resp) VG=function(trat, resp, sample.curve=1000, error = "SE", ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", r2 = "mean", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, yname.formula="y", xname.formula="x", comment = NA, fontfamily="sans") { if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) model <- lm(resp ~ I(sqrt(trat))) coef=summary(model) if(is.na(round)==TRUE){ a=coef$coefficients[,1][1] b=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ a=round(coef$coefficients[,1][1],round) b=round(coef$coefficients[,1][2],round)} modm=lm(ymean~I(sqrt(xmean))) if(r2=="all"){r2=round(summary(model)$r.squared,2)} if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %e %s %e * sqrt(%s) ~~~~~ italic(R^2) == %0.2f", yname.formula, coef(modm)[1], ifelse(coef(modm)[2] >= 0, "+", "-"), abs(coef(modm)[2]), xname.formula, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/VG_analysis.R
#' Utils: Adjust y and x scale #' #' Adjust y and x scale for chart or charts #' #' @param plots Object of analysis or plot_arrange #' @param scale.x x-axis scale (use vector) #' @param limits.x limits in x-axis (use vector) #' @param scale.y y-axis scale (use vector) #' @param limits.y limits in y-axis (use vector) #' #' @return Returns the scaled graph #' @export #' #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' a=LM(trat,resp) #' b=LL(trat,resp,npar = "LL.3") #' a=plot_arrange(list(a,b),gray = TRUE) #' adjust_scale(a,scale.y = seq(0,100,10),limits.y = c(0,100)) adjust_scale=function(plots, scale.x="default", limits.x="default", scale.y="default", limits.y="default"){ if(length(plots)==3 | length(plots)==3){plots=plots[[3]]}else{plots=plots} requireNamespace("ggplot2") if(limits.y[1]=="default"){limits.y=c(min(plots$plot$data$y), max(plots$plot$data$y))} if(scale.y[1]!="default"){plots=plots+ scale_y_continuous(breaks=scale.y,limits = limits.y)} if(limits.x[1]=="default"){limits.x=c(min(plots$plot$data$x), max(plots$plot$data$x))} if(scale.x[1]!="default"){plots=plots+ scale_x_continuous(breaks=scale.x,limits = limits.x)} plots }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/adjust_scale.R
#' Utils: Adjust x scale #' #' Adjust x scale for chart or charts #' #' @param plots Object of analysis or plot_arrange #' @param scale x-axis scale (use vector) #' @param limits limits in x-axis (use vector) #' #' @return Returns the scaled graph #' @export #' #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' a=LM(trat,resp) #' b=LL(trat,resp,npar = "LL.3") #' a=plot_arrange(list(a,b),gray = TRUE) #' adjust_scale_x(a,scale = seq(10,40,5),limits = c(10,40)) adjust_scale_x=function(plots, scale="default", limits="default"){ if(length(plots)==3 | length(plots)==3){plots=plots[[3]]}else{plots=plots} requireNamespace("ggplot2") if(limits[1]=="default"){limits=c(min(plots$plot$data$x), max(plots$plot$data$x))} if(scale[1]!="default"){plots=plots+ scale_x_continuous(breaks=scale,limits = limits)} plots }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/adjust_scale_x.R
#' Utils: Adjust y scale #' #' Adjust y scale for chart or charts #' #' @param plots Object of analysis or plot_arrange #' @param scale y-axis scale (use vector) #' @param limits limits in y-axis (use vector) #' #' @return Returns the scaled graph #' @export #' #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' a=LM(trat,resp) #' b=LL(trat,resp,npar = "LL.3") #' a=plot_arrange(list(a,b),gray = TRUE) #' adjust_scale_y(a,scale = seq(0,100,10),limits = c(0,100)) adjust_scale_y=function(plots, scale="default", limits="default"){ if(length(plots)==3 | length(plots)==3){plots=plots[[3]]}else{plots=plots} requireNamespace("ggplot2") if(limits[1]=="default"){limits=c(min(plots$plot$data$y), max(plots$plot$data$y))} if(scale[1]!="default"){plots=plots+ scale_y_continuous(breaks=scale,limits = limits)} plots }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/adjust_scale_y.R
#' Dataset: Aristolochia #' #' The data come from an experiment conducted at the Seed Analysis #' Laboratory of the Agricultural Sciences Center of the State #' University of Londrina, in which five temperatures (15, 20, 25, #' 30 and 35C) were evaluated in the germination of \emph{Aristolochia elegans}. #' The experiment was conducted in a completely randomized #' design with four replications of 25 seeds each. #' #' @docType data #' #' @usage data("aristolochia") #' #' @format data.frame containing data set #' \describe{ #' \item{\code{trat}}{Numeric vector with temperature} #' \item{\code{resp}}{Numeric vector with response} #' } #' @author Hugo Roldi Guariz #' @keywords datasets #' @examples #' data(aristolochia) "aristolochia"
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/aristolochia_dataset.R
#' Analysis: Asymptotic, exponential or Logarithmic #' #' This function performs asymptotic regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param fontfamily Font family #' @param comment Add text after equation #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The exponential model is defined by: #' \deqn{y = \alpha \times e^{-\beta \cdot x} + \theta} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley and Sons (p. 330). #' @export #' #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' asymptotic(time,100-WL) asymptotic=function(trat, resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) theta.0 = min(resp) * 0.5 model.0 = lm(log(resp - theta.0) ~ trat) alpha.0 = exp(coef(model.0)[1]) beta.0 = coef(model.0)[2] start = list(alpha = alpha.0, beta = -beta.0, theta = theta.0) model = nls(resp ~ alpha * exp(-beta * trat) + theta ,start = start) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 = nls(ymean ~ alpha * exp(-beta * xmean) + theta ,start = start) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*e^{%s %0.3e*%s} %s %0.3e ~~~~~ italic(R^2) == %0.2f", yname.formula, b, ifelse(d <= 0, "","-"), abs(d), xname.formula, ifelse(e <= 0, "-","+"), abs(e), r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black", family = fontfamily), axis.title = element_text(size=textsize,color="black",family=fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/asymptotic_analysis.R
#' Analysis: Asymptotic without intercept #' #' This function performs asymptotic regression analysis without intercept. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param fontfamily Font family #' @param comment Add text after equation #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The asymptotic model without intercept is defined by: #' \deqn{y = \alpha \times e^{-\beta \cdot x}} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley and Sons (p. 330). #' @references Siqueira, V. C., Resende, O., & Chaves, T. H. (2013). Mathematical modelling of the drying of jatropha fruit: an empirical comparison. Revista Ciencia Agronomica, 44, 278-285. #' @export #' #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' asymptotic_i(time,100-WL) asymptotic_i=function(trat, resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", fontfamily="sans", comment=NA){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) theta.0 = min(resp) * 0.5 model.0 = lm(log(resp - theta.0) ~ trat) alpha.0 = exp(coef(model.0)[1]) beta.0 = coef(model.0)[2] start = list(alpha = alpha.0, beta = -beta.0) model = nls(resp ~ alpha * exp(-beta * trat), start = start) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 = nls(ymean ~ alpha * exp(-beta * xmean), start = start) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*e^{%s %0.3e*%s} ~~~~~ italic(R^2) == %0.2f", yname.formula, b, ifelse(d <= 0, "+","-"), abs(d), xname.formula, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black", family = fontfamily), axis.title = element_text(size=textsize,color="black", family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize, family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/asymptotic_i_analysis.R
#' Analysis: Asymptotic or Exponential Negative without intercept #' #' This function performs asymptotic regression analysis without intercept. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param fontfamily Font family #' @param comment Add text after equation #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Siqueira, V. C., Resende, O., & Chaves, T. H. (2013). Mathematical modelling of the drying of jatropha fruit: an empirical comparison. Revista Ciencia Agronomica, 44, 278-285. #' @export #' @details #' The asymptotic negative model without intercept is defined by: #' \deqn{y = \alpha \times e^{-\beta \cdot x}} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' asymptotic_ineg(time,100-WL) asymptotic_ineg=function(trat, resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) data=data.frame(trat,resp) theta.0 = max(data$resp) * 1.1 model.0 = lm(log(- resp + theta.0) ~ trat, data=data) alpha.0 = exp(coef(model.0)[1]) beta.0 = coef(model.0)[2] start = list(alpha = -alpha.0, beta = -beta.0) model = nls(resp ~ -alpha * exp(-beta * trat), data = data, start = start) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 = nls(ymean ~ -alpha * exp(-beta * xmean), start = start) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%s %0.3e*e^{%s %0.3e*%s} ~~~~~ italic(R^2) == %0.2f", yname.formula, ifelse(b <= 0, "","-"), abs(b), ifelse(d <= 0, "","-"), abs(d), xname.formula, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black", family=fontfamily), axis.title = element_text(size=textsize,color="black", family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize, family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/asymptotic_i_sup_analysis.R
#' Analysis: Asymptotic or Exponential Negative #' #' This function performs asymptotic regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @export #' @details #' The asymptotic model is defined by: #' \deqn{y = -\alpha \times e^{-\beta \cdot x}+\theta} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' asymptotic_neg(time,WL) asymptotic_neg=function(trat, resp, sample.curve=1000, ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) data=data.frame(trat,resp) theta.0 = max(data$resp) * 1.1 model.0 = lm(log(- resp + theta.0) ~ trat, data=data) alpha.0 = -exp(coef(model.0)[1]) beta.0 = coef(model.0)[2] start = list(alpha = -alpha.0, beta = -beta.0, theta = theta.0) model = nls(resp ~ -alpha * exp(-beta * trat) + theta , data = data, start = start) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=cor(resp, fitted(model))^2} if(r2=="mean"){r2=cor(ymean, predict(model,newdata=data.frame(trat=unique(trat))))^2} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 = nls(ymean ~ -alpha * exp(-beta * xmean)+theta, start = start) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%s %0.3e*e^{%s %0.3e*%s} %s %0.3e ~~~~~ italic(R^2) == %0.2f", yname.formula, ifelse(b <= 0, "+","-"), abs(b), ifelse(d <= 0, "+","-"), abs(d), xname.formula, ifelse(e <= 0, "-","+"), abs(e), r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black", family=fontfamily), axis.title = element_text(size=textsize,color="black", family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/asymptotic_sup_analysis.R
#' Analysis: Beta #' #' This function performs beta regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position Legend position (\emph{default} is "top") #' @param r2 Coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point Defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize Shape size #' @param linesize Line size #' @param linetype line type #' @param pointshape Format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The beta model is defined by: #' \deqn{Y = d \times \{(\frac{X-X_b}{X_o-X_b})(\frac{X_c-X}{X_c-X_o})^{\frac{X_c-X_o}{X_o-X_b}}\}^b} #' @author Model imported from the aomisc package (Andrea Onofri) #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Onofri, A., 2020. The broken bridge between biologists and statisticians: a blog and R package. Statforbiology. http://www.statforbiology.com/tags/aomisc/ #' @export #' @examples #' library(AgroReg) #' X <- c(1, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50) #' Y <- c(0, 0, 0, 7.7, 12.3, 19.7, 22.4, 20.3, 6.6, 0, 0) #' beta_reg(X,Y) beta_reg=function(trat, resp, sample.curve=1000, ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} beta.fun <- function(X, b, d, Xb, Xo, Xc){ .expr1 <- (X - Xb)/(Xo - Xb) .expr2 <- (Xc - X)/(Xc - Xo) .expr3 <- (Xc - Xo)/(Xo - Xb) ifelse(X > Xb & X < Xc, d * (.expr1*.expr2^.expr3)^b, 0)} DRC.beta <- function(){ fct <- function(x, parm) { beta.fun(x, parm[,1], parm[,2], parm[,3], parm[,4], parm[,5]) } ssfct <- function(data){ x <- data[, 1] y <- data[, 2] d <- max(y) Xo <- x[which.max(y)] firstidx <- min( which(y !=0) ) Xb <- ifelse(firstidx == 1, x[1], (x[firstidx] + x[(firstidx - 1)])/2) secidx <- max( which(y !=0) ) Xc <- ifelse(secidx == length(y), x[length(x)], (x[secidx] + x[(secidx + 1)])/2) c(1, d, Xb, Xo, Xc) } names <- c("b", "d", "Xb", "Xo", "Xc") text <- "Beta function" returnList <- list(fct = fct, ssfct = ssfct, names = names, text = text) class(returnList) <- "drcMean" invisible(returnList)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) model <- drm(resp~trat,fct=DRC.beta()) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] Xb=coef$coefficients[,1][3] Xo=coef$coefficients[,1][4] Xc=coef$coefficients[,1][5]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) Xb=round(coef$coefficients[,1][3],round) Xo=round(coef$coefficients[,1][4],round) Xc=round(coef$coefficients[,1][5],round)} if(r2=="all"){r2=cor(resp, fitted(model))^2} if(r2=="mean"){r2=cor(ymean, predict(model, newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 xoxb=Xo-Xb xcxo=Xc-Xo xcxoxoxb=(Xc-Xo)/(Xo-Xb) equation=sprintf("~~~%s==%0.3e*bgroup(\"{\",group(\"(\",frac(%s %s %0.3e, %0.3e),\")\")*group(\"(\",frac(%0.3e-%s, %0.3e),\")\")^%0.3e,\"}\")^%0.3e ~~~~~ italic(R^2) == %0.2f", yname.formula, d, xname.formula, ifelse(Xb >= 0, "+", "-"), abs(Xb), xoxb, Xc, xname.formula, xcxo, xcxoxoxb, b, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black", family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize, family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/beta_analysis.R
#' Change the colors of a graph from the plot_arrange function #' @param graphs object from a plot_arrange function #' @param color color curve and point #' @return The function changes the colors of a graph coming from the plot_arrange function #' @author Gabriel Danilo Shimizu #' @export #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' graph1=LM(trat,resp) #' graph2=LL(trat,resp,npar = "LL.3") #' graph=plot_arrange(list(graph1,graph2)) #' coloredit_arrange(graph,color=c("red","blue")) coloredit_arrange = function(graphs, color = NA) { if (is.na(color[1]) == TRUE) { graphs = graphs + scale_color_discrete(labels = parse(text = graphs$plot$equation)) } if (is.na(color[1]) == FALSE) { graphs = graphs + scale_color_manual(values = color, labels = parse(text = graphs$plot$equation)) } graphs }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/color_edition.R
#' Analysis: Comparative models #' #' This function allows the construction of a table and/or graph with the statistical parameters to choose the model from the analysis functions. #' @param models List with objects of type analysis #' @param names_model Names of the models #' @param plot Plot in the parameters #' @param round.label Round label plot #' @return Returns a table and/or graph with the statistical parameters for choosing the model. #' @author Gabriel Danilo Shimizu #' @export #' @examples #' library(AgroReg) #' data(granada) #' attach(granada) #' a=LM(time,WL) #' b=LL(time,WL) #' c=BC(time,WL) #' d=weibull(time,WL) #' comparative_model(models=list(a,b,c,d),names_model=c("LM","LL","BC","Weibull")) #' #' models <- c("LM1", "LM4", "L3", "BC4,"weibull3","mitscherlich", "linear.plateau", "VG") #' r <- lapply(models, function(x) { #' r <- with(granada, regression(time, WL, model = x)) #' }) #' comparative_model(r,plot = TRUE) #' @importFrom egg ggarrange comparative_model=function(models, names_model=NA, plot=FALSE, round.label=2){ tabela=matrix(rep(NA,length(models)*4),ncol=4) for(i in 1:length(models)){ tabela[i,]=c(models[[i]]$values[5:8,2])} tabela=data.frame(tabela) if(is.na(names_model[1])==TRUE){rownames(tabela)= paste("Model",1:length(models))}else{ rownames(tabela)=names_model} colnames(tabela)=c("AIC","BIC","R2","RMSE") requireNamespace("ggplot2") if(plot==TRUE){ modelo=rownames(tabela) R2=tabela$R2 RMSE=tabela$RMSE a=ggplot(tabela,aes(y=modelo,x=AIC))+ geom_col(aes(fill=modelo),color="black", show.legend = FALSE,size=1)+ geom_label(aes(x=(AIC/2),label=round(AIC,round.label)),show.legend = FALSE)+ theme_bw()+labs(y="Models")+ theme(axis.text = element_text(size=12,color="black"), axis.title = element_text(size=12)) b=ggplot(tabela,aes(y=modelo,x=BIC))+ geom_col(aes(fill=modelo),color="black", show.legend = FALSE,size=1)+ geom_label(aes(x=(BIC/2),label=round(BIC,round.label)), show.legend = FALSE)+ theme_bw()+labs(y="Models")+ theme(axis.text.y = element_blank(), axis.title.y = element_blank(), axis.text.x = element_text(size=12,color="black"), axis.title.x = element_text(size=12)) c=ggplot(tabela,aes(y=modelo,x=R2))+ geom_col(aes(fill=modelo),color="black", show.legend = FALSE,size=1)+ theme_bw()+labs(y="Models",x=expression(R^2))+ geom_label(aes(x=(R2/2),label=round(R2,2)),show.legend = FALSE)+ theme(axis.text.y = element_blank(), axis.title.y = element_blank(), axis.text.x = element_text(size=12,color="black"), axis.title.x = element_text(size=12)) d=ggplot(tabela,aes(y=modelo,x=RMSE))+ geom_col(aes(fill=modelo),color="black", show.legend = FALSE,size=1)+ theme_bw()+labs(y="Models")+ geom_label(aes(x=(RMSE/2),label=round(RMSE,round.label)),show.legend = FALSE)+ theme(axis.text.y = element_blank(), axis.title.y = element_blank(), axis.text.x = element_text(size=12,color="black"), axis.title.x = element_text(size=12)) egg::ggarrange(a,b,c,d,nrow=1)} tabela}
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/comparative_function.R
#' Graph: Plot correlation #' #' @description Correlation analysis function (Pearson or Spearman) #' @param x Numeric vector with independent variable #' @param y Numeric vector with dependent variable #' @param method Method correlation (\emph{default} is Pearson) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param textsize Axis text size #' @param pointsize Point size #' @param pointshape shape format #' @param linesize line size #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param title title #' @param fontfamily Font family #' @author Gabriel Danilo Shimizu, \email{[email protected]} #' @author Leandro Simoes Azeredo Goncalves #' @return The function returns a graph for correlation #' @importFrom stats cor #' @importFrom stats cor.test #' @export #' @examples #' data("aristolochia") #' with(aristolochia, correlation(trat,resp)) correlation = function(x, y, method = "pearson", ylab = "Dependent", xlab = "Independent", theme = theme_classic(), textsize = 12, pointsize = 5, pointshape = 21, linesize = 0.8, fill.ic = "gray70", alpha.ic = 0.5, ic = TRUE, title = NA, fontfamily = "sans") { if(is.na(title)==TRUE){ if(method=="pearson"){title="Pearson correlation"} if(method=="spearman"){title="Spearman correlation"} } if(method=="pearson"){corre=cor(y,x) pvalor=cor.test(y,x,method="pearson",exact=FALSE)$p.value} if(method=="spearman"){corre=cor(y,x,method = "spearman") pvalor=cor.test(y,x,method="spearman",exact=FALSE)$p.value} requireNamespace("ggplot2") data=data.frame(y,x) ggplot(data,aes(y=y,x=x))+ geom_point(shape=pointshape,fill="gray",color="black",size=pointsize)+ geom_smooth( color = "black", se = ic, size = linesize, fill = fill.ic, alpha = alpha.ic, na.rm = TRUE, method = "lm")+ theme+labs(title=title,x=xlab,y=ylab)+ theme(axis.text = element_text(size=textsize, color="black",family = fontfamily), axis.title = element_text(family = fontfamily))+ annotate(geom = "text",x = -Inf,y=Inf, label=paste("R = ", round(corre,2), ", p-value =", format(round(pvalor,3),scientific = TRUE),sep = ""), hjust = -0.1, vjust = 1.1) }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/correlation_analysis.R
#' Analysis: Extract models #' #' @description This function allows extracting the model (type="model") or residuals (type="resids"). The model class depends on the function and can be (lm, drm or nls). This function also allows you to perform graphical analysis of residuals (type="residplot"), graphical analysis of standardized residuals (type="stdresidplot"), graph of theoretical quantiles (type="qqplot"). #' @param model Object returned from an analysis function #' @param type output type #' @export #' @return Returns an object of class drm, lm or nls (type="model"), or vector of residuals (type="resids"), or graph of the residuals (type="residplot", type="stdresidplot", type=" qqplot"). #' @importFrom stats resid #' @importFrom stats qnorm #' @importFrom stats quantile #' @examples #' #' data("aristolochia") #' attach(aristolochia) #' a=linear.linear(trat,resp,point = "mean") #' extract.model(a,type = "qqplot") extract.model=function(model,type="model"){ if(type=="model"){results=model$plot$plot$model} if(type=="resid"){results=resid(model$plot$plot$model)} if(type=="residplot"){ resids=resid(model$plot$plot$model) data=data.frame(ID=1:length(resids),resids) requireNamespace("ggplot2") results=ggplot(data,aes(x=ID,y=resids))+ geom_hline(yintercept = 0,lty=2, size=1)+ geom_point(shape=21,color="black",fill="lightblue",size=4.5)+ geom_text(aes(label=ID),color="red")+ theme_classic()+ ylab("Residuals")+ theme(axis.text = element_text(size=12))} if(type=="stdresidplot"){ resids=resid(model$plot$plot$model) resids=resids/sd(resids) ID=1:length(resids) data=data.frame(ID=ID,resids) requireNamespace("ggplot2") results=ggplot(data,aes(x=ID,y=resids))+ geom_hline(yintercept = c(3,0,-3),lty=2, color=c("red","black","red"), size=1)+ geom_point(shape=21,color="black",fill="lightblue",size=4.5)+ geom_text(aes(label=ID),color="red")+ theme_classic()+ ylab("Standart residuals")+ #scale_x_continuous(breaks=seq(1,length(resids)))+ theme(axis.text = element_text(size=12))} if(type=="qqplot"){ yres=sort(resid(model$plot$plot$model)) distribution = qnorm probs=c(0.25,0.75) stopifnot(length(probs) == 2, is.function(distribution)) y <- quantile(yres, c(0.25,0.75), names = FALSE, type = 7, na.rm = TRUE) x <- distribution(probs) slope <- diff(y)/diff(x) int <- y[1L] - slope * x[1L] data=data.frame(ID=1:length(yres),yres) requireNamespace("ggplot2") results=ggplot(data,aes(sample=yres))+ stat_qq(alpha=0.5,size=4.5,shape=21,fill="blue",color="black")+ geom_abline(slope = slope, intercept = int, color="black", size=1, lty=2)+ theme_classic()+ ylab("Sample Quantiles")+ xlab("Theoretical Quantiles")+ theme(axis.text = element_text(size=12))} results}
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/extractmodel_analysis.R
#' Analysis: Analogous to the Gaussian model/Bragg #' #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar number of parameters (g3 or g4) #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @importFrom stats var #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The model analogous to the three-parameter Gaussian is: #' \deqn{y = d \times e^{-b((x-e)^2)}} #' The model analogous to the three-parameter Gaussian is: #' \deqn{y = d \times c+(d-c)*e^{-b((x-e)^2)}} #' @export #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' gaussianreg(trat,resp) gaussianreg=function(trat, resp, npar="g3", sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), error="SE", legend.position="top", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) bragg.3.fun <- function(X, b, d, e){ d * exp(- b * (X - e)^2)} DRC.bragg.3 <- function(){ fct <- function(x, parm){bragg.3.fun(x, parm[,1], parm[,2], parm[,3])} ssfct <- function(data){ x <- data[, 1] y <- data[, 2] d <- max(y) e <- x[which.max(y)] pseudoY <- log( (y + 0.0001) / d ) pseudoX <- (x - e)^2 coefs <- coef( lm(pseudoY ~ pseudoX - 1) ) b <- - coefs[1] start <- c(b, d, e) return( start)} names <- c("b", "d", "e") text <- "Bragg equation with three parameters" returnList <- list(fct = fct, ssfct = ssfct, names = names, text = text) class(returnList) <- "drcMean" invisible(returnList)} bragg.4.fun <- function(X, b, c, d, e){ c + (d - c) * exp(- b * (X - e)^2)} DRC.bragg.4 <- function(){ fct <- function(x, parm) { bragg.4.fun(x, parm[,1], parm[,2], parm[,3], parm[,4])} ssfct <- function(data){ x <- data[, 1] y <- data[, 2] d <- max(y) c <- min(y) * 0.95 e <- x[which.max(y)] pseudoY <- log( ((y + 0.0001) - c) / d ) pseudoX <- (x - e)^2 coefs <- coef( lm(pseudoY ~ pseudoX - 1) ) b <- - coefs[1] start <- c(b, c, d, e) return( start)} names <- c("b", "c", "d", "e") text <- "Bragg equation with four parameters" returnList <- list(fct = fct, ssfct = ssfct, names = names, text = text) class(returnList) <- "drcMean" invisible(returnList)} if(npar=="g3"){ mod=drm(resp ~ trat, fct = DRC.bragg.3()) mod=nls(resp ~ d*exp(-b*(trat-e)^2),start = list(b=coef(mod)[1], d=coef(mod)[2], e=coef(mod)[3])) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} # if(r2=="all"){r2=cor(resp, fitted(mod))^2} # if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1=nls(ymean ~ d*exp(-b*(xmean-e)^2),start = list(b=coef(mod)[1], d=coef(mod)[2], e=coef(mod)[3])) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*e^{%s %0.3e(%s %s %0.3e)^2} ~~~~~ italic(R^2) == %0.2f", yname.formula, d, ifelse(b <= 0, "+", "-"), abs(b), xname.formula, ifelse(e <= 0, "+", "-"), abs(e), r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")}} if(npar=="g4"){ mod=drm(resp ~ trat, fct = DRC.bragg.4()) mod=nls(resp ~ c+(d-c)*exp(-b*(trat-e)^2),start = list(b=coef(mod)[1], c=coef(mod)[2], d=coef(mod)[3], e=coef(mod)[4])) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] dc=d-c e=coef$coefficients[,1][4]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) dc=d-c e=round(coef$coefficients[,1][4],round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~y==%0.3e %s %0.3e*e^{%s %0.3e(x %s %0.3e)^2} ~~~~~ italic(R^2) == %0.2f", c, ifelse(dc >= 0, "+", "-"), abs(dc), ifelse(b <= 0, "+", "-"), abs(b), ifelse(e >= 0, "+", "-"), abs(e), r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")}} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/gaussian_analysis.R
#' Analysis: Gompertz #' #' The logistical models provide Gompertz modified logistical models. This model was extracted from the 'drc' package. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar Number os parameters (g2, g3 or g4) #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The two-parameter Gompertz model is given by the function: #' \deqn{y = exp^{-exp^{b(x-e)}}} #' The three-parameter Gompertz model is given by the function: #' \deqn{y = d \times exp^{-exp^{b(x-e)}}} #' The four-parameter Gompertz model is given by the function: #' \deqn{y = c + (d-c)(exp^{-exp^{b(x-e)}})} #' @export #' @seealso \link{LL}, \link{CD}, \link{BC} #' @author Model imported from the drc package (Ritz et al., 2016) #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley and Sons (p. 330). #' @references Ritz, C.; Strebig, J.C. and Ritz, M.C. Package ‘drc’. Creative Commons: Mountain View, CA, USA, 2016. #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' GP(trat,resp, npar="g3") GP=function(trat, resp, npar="g2", sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, error="SE", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd if(npar=="g2"){ mod=drm(resp~trat,fct=G.2()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] e=coef$coefficients[,1][4]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) e=round(coef$coefficients[,1][4],round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==e^(-e^(%0.3e*(%s %s %0.3e))) ~~~~~ italic(R^2) == %0.2f", yname.formula, b, xname.formula, ifelse(e <= 0,"+","-"), e, r2)} if(npar=="g3"){ mod=drm(resp~trat,fct=G.3()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*e^{-e^{%0.3e*(%s %s %0.3e)}} ~~~~~ italic(R^2) == %0.2f", yname.formula, d, b, xname.formula, ifelse(e <= 0,"+","-"), abs(e), r2)} if(npar=="g4"){ mod=drm(resp~trat,fct=G.4()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~y==%0.3e %s %0.3e*e^{-e^{%0.3e*(x %s %0.3e)}} ~~~~~ italic(R^2) == %0.2f", c, ifelse(d-c >= 0,"+","-"), abs(d-c), b, ifelse(e <= 0,"+","-"), abs(e), r2)} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(ic==TRUE){ pred=data.frame(x=xp, y=predict(mod,interval = "confidence",newdata = data.frame(trat=xp))) preditosic=data.frame(x=c(pred$x,pred$x[length(pred$x):1]), y=c(pred$y.Lower,pred$y.Upper[length(pred$x):1])) graph=graph+geom_polygon(data=preditosic,aes(x=x,y),fill=fill.ic,alpha=alpha.ic)} graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1), type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/gompertz_analysis.R
#' Dataset: Granada #' #' The data are part of an experiment that studied the drying #' kinetics of pomegranate peel over time under an air-circulation #' oven. Mass loss was assessed. #' #' @docType data #' #' @usage data("granada") #' #' @format data.frame containing data set #' \describe{ #' \item{\code{time}}{numeric vector with times} #' \item{\code{WL}}{Numeric vector with response} #' } #' @author Gabriel Danilo Shimizu #' @keywords datasets #' @examples #' data(granada) "granada"
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/granada_dataset.R
#' Analysis: Hill #' #' This function performs regression analysis using the Hill model. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @details #' The Hill model is defined by: #' \deqn{y = \frac{a \times x^c}{b+x^c}} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @export #' @author Model imported from the aomisc package (Onofri, 2020) #' @author Gabriel Danilo Shimizu #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Onofri A. (2020) The broken bridge between biologists and statisticians: a blog and R package, Statforbiology, IT, web: https://www.statforbiology.com #' @examples #' data("granada") #' attach(granada) #' hill(time,WL) #' @md hill=function(trat, resp, sample.curve=1000, error = "SE", ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", point = "all", width.bar = NA, r2 = "all", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd DRC.hill<-function(fixed = c(NA, NA, NA), names = c("a", "b", "c")){ hillCurveMean <- function(predictor, a, b, c) { (a * predictor^c)/(b + predictor^c)} numParm <- 3 if (!is.character(names) | !(length(names) == numParm)) {stop("Not correct 'names' argument")} if (!(length(fixed) == numParm)) {stop("Not correct 'fixed' argument")} notFixed <- is.na(fixed) parmVec <- rep(0, numParm) parmVec[!notFixed] <- fixed[!notFixed] fct <- function(x, parm){ parmMat <- matrix(parmVec, nrow(parm), numParm, byrow = TRUE) parmMat[, notFixed] <- parm a <- parmMat[, 1]; b <- parmMat[, 2]; c <- parmMat[, 3] (a * x^c)/(b + x^c)} ssfct <- function(dataf){ x <- dataf[, 1] y <- dataf[, 2] a <- max(y) * 1.05 pseudoY <- log(( a - y )/ y) pseudoX <- log(x) coefs <- coef( lm(pseudoY ~ pseudoX ) ) b <- exp(coefs[1]) c <- - coefs[2] return(c(a, b, c)[notFixed])} pnames <- names[notFixed] text <- "Hill function (Morgan-Mercer-Flodin)" returnList <- list(fct = fct, ssfct = ssfct, names = pnames, text = text, noParm = sum(is.na(fixed))) class(returnList) <- "drcMean" invisible(returnList)} mod=drm(resp~trat,fct=DRC.hill()) mod=nls(resp~(a * trat^c)/(b + trat^c), start = list(a=coef(mod)[1], b=coef(mod)[2], c=coef(mod)[3])) model=mod coef=summary(mod) if(is.na(round)==TRUE){ a=coef$coefficients[,1][1] b=coef$coefficients[,1][2] c=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ a=round(coef$coefficients[,1][1],round) b=round(coef$coefficients[,1][2],round) c=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 <- nls(ymean~(a * xmean^c)/(b + xmean^c), start = list(a=coef(mod)[1], b=coef(mod)[2], c=coef(mod)[3])) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s== frac(%0.3e * %s ^ %0.3e, %0.3e + %s ^%0.3e) ~~~~~ italic(R^2) == %0.2f", yname.formula, a, xname.formula, c, b, xname.formula, c, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+ geom_line(data=preditos,aes(x=x,y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize, family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1), type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/hill_analysis.R
#' Analysis: Linear-Linear #' #' This function performs linear linear regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param middle A scalar in [0,1]. This represents the range that the change-point can occur in. 0 means the change-point must occur at the middle of the range of x-values. 1 means that the change-point can occur anywhere along the range of the x-values. #' @param CI Whether or not a bootstrap confidence interval should be calculated. Defaults to FALSE because the interval takes a non-trivial amount of time to calculate #' @param bootstrap.samples The number of bootstrap samples to take when calculating the CI. #' @param sig.level What significance level to use for the confidence intervals. #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param legend.position legend position (\emph{default} is "top") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @import purrr #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); breakpoint and the graph using ggplot2 with the equation automatically. #' @details #' The linear-linear model is defined by: #' First curve: #' \deqn{y = \beta_0 + \beta_1 \times x (x < breakpoint)} #' #' Second curve: #' \deqn{y = \beta_0 + \beta_1 \times breakpoint + w \times x (x > breakpoint)} #' #' @export #' @author Model imported from the SiZer package #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Chiu, G. S., R. Lockhart, and R. Routledge. 2006. Bent-cable regression theory and applications. Journal of the American Statistical Association 101:542-553. #' @references Toms, J. D., and M. L. Lesperance. 2003. Piecewise regression: a tool for identifying ecological thresholds. Ecology 84:2034-2041. #' @seealso \link{quadratic.plateau}, \link{linear.plateau} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' linear.linear(time,WL) linear.linear=function (trat, resp, middle = 1, CI = FALSE, bootstrap.samples = 1000, sig.level = 0.05, error = "SE", ylab = "Dependent", xlab = "Independent", theme = theme_classic(), point = "all", width.bar = NA, legend.position = "top", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("purrr") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} piecewise.linear.simple <- function(x, y, middle=1){ piecewise.linear.likelihood <- function(alpha, x, y){ N <- length(x); w <- (x-alpha); w[w<0] <- 0; fit <- stats::lm(y ~ x + w); Beta <- stats::coefficients(fit); Mu <- Beta[1] + Beta[2]*x + Beta[3]*w; SSE <- sum(fit$residuals^2); sigma2 <- SSE/N; # MLE estimate of sigma^2 likelihood <- sum( log( stats::dnorm(y, mean=Mu, sd=sqrt(sigma2)) ) ); return(likelihood); } r <- range(x); offset <- r * (1-middle)/2; low <- min(x) + offset; high <- max(x) - offset; temp <- stats::optimize(piecewise.linear.likelihood, c(low, high), x=x, y=y, maximum=TRUE); return(temp$maximum); } x=trat y=resp alpha <- piecewise.linear.simple(x, y, middle) w <- x - alpha w[w < 0] <- 0 model <- stats::lm(y ~ x + w) out <- NULL out$change.point <- alpha out$model <- model out$x <- seq(min(x), max(x), length = 1000) w <- out$x - alpha w[w < 0] <- 0 out$y <- stats::predict(out$model, data.frame(x = out$x, w = w)) out$CI <- CI class(out) <- "PiecewiseLinear" if (CI == TRUE){ data <- data.frame(x = x, y = y) my.cp <- function(data, index) { x <- data[index, 1] y <- data[index, 2] cp <- piecewise.linear.simple(x, y) w <- x - cp w[w < 0] <- 0 model <- stats::lm(y ~ x + w) out <- c(cp, model$coefficients[2], model$coefficients[3], model$coefficients[2] + model$coefficients[3]) return(out) } boot.result <- boot::boot(data, my.cp, R = bootstrap.samples) out$intervals <- apply(boot.result$t, 2, stats::quantile, probs = c(sig.level/2, 1 - sig.level/2)) colnames(out$intervals) <- c("Change.Point", "Initial.Slope", "Slope.Change", "Second.Slope") out$CI <- t(out$CI) } ymean=tapply(y,x,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(x,x,mean) mod=out breaks=mod$change.point if(is.na(round)==TRUE){ b0=mod$model$coefficients[1] b1=mod$model$coefficients[2] b11=mod$model$coefficients[3]} if(is.na(round)==FALSE){ b0=round(mod$model$coefficients[1],round) b1=round(mod$model$coefficients[2],round) b11=round(mod$model$coefficients[3],round)} r2=round(summary(mod$model)$r.squared,2) r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e %s %0.3e*%s~(%s~'<'~%0.3e)~%s %0.3e*%s~(%s>%0.3e)~~~R^2==%0.2e", yname.formula, b0, ifelse(b1 >= 0, "+", "-"), abs(b1), xname.formula, xname.formula, breaks, ifelse(b11 >= 0, "+", "-"), abs(b11), xname.formula, xname.formula, breaks, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} s=equation temp1=mod$x result=mod$y preditos1=data.frame(x=temp1, y=result) data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) model=mod$model result1=predict(mod$model) rmse=sqrt(mean((result1-resp)^2)) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+ geom_line(data=preditos1,aes(x=x,y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) maximo=breaks respmax=predict(mod$model,newdata=data.frame(x=maximo,w=0)) minimo=NA respmin=NA aic=AIC(mod$model) bic=BIC(mod$model) graphs=data.frame("Parameter"=c("Breakpoint", "Breakpoint Response", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=summary(mod$model), "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/linearlinear_analysis.R
#' Analysis: loess regression (degree 0, 1 or 2) #' #' Fit a polynomial surface determined by one or more numerical predictors, using local fitting. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param degree Degree polynomial (0,1 or 2) #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param legend.position legend position (\emph{default} is c(0.3,0.8)) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param fontfamily Font family #' @return The function returns a list containing the loess regression and graph using ggplot2. #' @seealso \link{loess} #' @export #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' loessreg(trat,resp) loessreg=function(trat, resp, degree=2, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", fontfamily="sans"){ requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) mod=loess(resp~trat,degree = degree) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) s="~~~ Loess~regression" if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+ geom_line(data=preditos,aes(x=preditos$x, y=preditos$y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label="Loess regression")+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum"), "values"=c(maximo, respmax, minimo, respmin)) graficos=list("Coefficients"=NA, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/loess_analysis.R
#' Analysis: Logistic #' #' Logistic models with three (L.3), four (L.4) or five (L.5) continuous data parameters. This model was extracted from the drc package. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar Number of model parameters #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The three-parameter logistic function with lower limit 0 is #' \deqn{y = 0 + \frac{d}{1+\exp(b(x-e))}} #' The four-parameter logistic function is given by the expression #' \deqn{y = c + \frac{d-c}{1+\exp(b(x-e))}} #' The five-parameter logistic function is given by the expression #' \deqn{y = c + \frac{d-c}{1+\exp(b(x-e))^f}} #' The function is symmetric about the inflection point (e). #' @author Model imported from the drc package (Ritz et al., 2016) #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Ritz, C.; Strebig, J.C.; Ritz, M.C. Package ‘drc’. Creative Commons: Mountain View, CA, USA, 2016. #' @export #' #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' logistic(trat,resp) logistic=function(trat, resp, npar="L.3", sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ requireNamespace("drc") requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) if(npar=="L.3"){mod=drm(resp~trat,fct=L.3()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac(%0.3e, 1+e^{%0.3e*(%s %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, d, b, xname.formula, ifelse(e <=0,"+","-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) } if(npar=="L.5"){mod=drm(resp~trat,fct=L.5()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] f=coef$coefficients[,1][5] dc=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) f=round(coef$coefficients[,1][5],round) dc=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %0.3e + frac(%0.3e, 1+e^(%0.3e*(%s %s %0.3e))^%0.3e) ~~~~~ italic(R^2) == %0.2f", yname.formula, c, dc, b, xname.formula, ifelse(e <=0,"+","-"), abs(e), f, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} if(npar=="L.4"){mod=drm(resp~trat,fct=L.4()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] dc=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) dc=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %0.3e + frac(%0.3e, 1+e^{%0.3e*(%s %s %0.3e)}) ~~~~~ italic(R^2) == %0.2f", yname.formula, c, dc, b, xname.formula, ifelse(e <=0,"+","-"), abs(e), r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(ic==TRUE){ pred=data.frame(x=xp, y=predict(mod,interval = "confidence",newdata = data.frame(trat=xp))) preditosic=data.frame(x=c(pred$x,pred$x[length(pred$x):1]), y=c(pred$y.Lower,pred$y.Upper[length(pred$x):1])) graph=graph+geom_polygon(data=preditosic,aes(x=x,y),fill=fill.ic,alpha=alpha.ic)} graph=graph+ theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(temp=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/logistic_analysis.R
#' Analysis: Lorentz #' #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar number of parameters (lo3 or lo4) #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @importFrom stats var #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The model to the three-parameter Lorentz is: #' \deqn{y = frac{d}{1+b(x-e)^2}} #' The model to the three-parameter Lorentz is: #' \deqn{y = c+frac{d-c}{1+b(x-e)^2}} #' @export #' @author Model imported from the aomisc package (Onofri, 2020) #' @author Gabriel Danilo Shimizu #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Onofri A. (2020) The broken bridge between biologists and statisticians: a blog and R package, Statforbiology, IT, web: https://www.statforbiology.com #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' x=time[length(time):1] #' lorentz(x,WL) lorentz=function(trat, resp, npar = "lo3", sample.curve=1000, ylab = "Dependent", xlab = "Independent", theme = theme_classic(), error = "SE", legend.position = "top", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, xname.formula = "x", yname.formula = "y", comment = NA, fontfamily = "sans"){ requireNamespace("ggplot2") requireNamespace("drc") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) DRC.lorentz.3 <- function(){ lorentz.3.fun <- function(X, b, d, e){ d / ( 1 + b * (X - e)^2)} fct <- function(x, parm){lorentz.3.fun(x, parm[,1], parm[,2], parm[,3])} ssfct <- function(data){ x <- data[, 1] y <- data[, 2] d <- max(y) e <- x[which.max(y)] pseudoY <- ( d - y )/ y pseudoX <- (x - e)^2 coefs <- coef( lm(pseudoY ~ pseudoX - 1) ) b <- coefs[1] start <- c(b, d, e) return( start )} names <- c("b", "d", "e") text <- "Three parameters" returnList <- list(fct = fct, ssfct = ssfct, names = names, text = text) class(returnList) <- "drcMean" invisible(returnList)} DRC.lorentz.4 <- function(){ lorentz.4.fun <- function(X, b, c, d, e){ c + (d - c) / ( 1 + b * (X - e)^2)} fct <- function(x, parm) { lorentz.4.fun(x, parm[,1], parm[,2], parm[,3], parm[,4])} ssfct <- function(data){ x <- data[, 1] y <- data[, 2] d <- max(y) c <- min(y) * 0.95 e <- x[which.max(y)] pseudoY <- (d - y)/(y - c) pseudoX <- (x - e)^2 coefs <- coef( lm(pseudoY ~ pseudoX - 1) ) b <- coefs[1] start <- c(b, c, d, e) return(start)} names <- c("b", "c", "d", "e") text <- "Four parameters" returnList <- list(fct = fct, ssfct = ssfct, names = names, text = text) class(returnList) <- "drcMean" invisible(returnList)} if(npar=="lo3"){ mod=drm(resp ~ trat, fct = DRC.lorentz.3()) mod=nls(resp ~ d/(1+b*(trat-e)^2), start = list(b=coef(mod)[1], d=coef(mod)[2], e=coef(mod)[3])) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 <- nls(ymean ~ d/(1+b*(xmean-e)^2), start = list(b=coef(mod)[1], d=coef(mod)[2], e=coef(mod)[3])) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac(%0.3e,1 %s %0.3e(%s %s %0.3e)^2) ~~~~~ italic(R^2) == %0.2f", yname.formula, d, ifelse(b >= 0, "+", "-"), abs(b), xname.formula, ifelse(e <= 0, "+", "-"), abs(e), r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")}} if(npar=="lo4"){ mod=drm(resp ~ trat, fct = DRC.lorentz.4()) mod=nls(resp ~ c+(d-c)/(1+b*(trat-e)^2), start = list(b=coef(mod)[1], c=coef(mod)[2], d=coef(mod)[3], e=coef(mod)[4])) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] dc=d-c e=coef$coefficients[,1][4]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) dc=d-c e=round(coef$coefficients[,1][4],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 <- nls(ymean ~ c+(d-c)/(1+b*(xmean-e)^2), start = list(b=coef(mod)[1], c=coef(mod)[2], d=coef(mod)[3], e=coef(mod)[4])) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e + frac(%0.3e,1 %s %0.3e(%s %s %0.3e)^2) ~~~~~ italic(R^2) == %0.2f", yname.formula, c, dc, ifelse(b >= 0, "+", "-"), abs(b), xname.formula, ifelse(e >= 0, "+", "-"), abs(e), r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")}} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/lorentz_analysis.R
#' Analysis: Midilli #' #' This function performs Midilli regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param initial List starting estimates #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The exponential model is defined by: #' \deqn{y = \alpha \times e^{-\beta \cdot x^n} + \theta \cdot x} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @export #' #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' midilli(time,100-WL) midilli=function(trat, resp, initial=NA, sample.curve=1000, ylab="Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) if(is.na(initial[1])==TRUE){ theta.0 <- min(resp) * 0.5 model.0 <- lm(log(resp - theta.0) ~ trat) alpha.0 <- exp(coef(model.0)[1]) beta.0 <- coef(model.0)[2] theta.0<-theta.0/mean(trat) n=1 initial <- list(alpha = alpha.0, beta = beta.0, theta = theta.0, n=n)} model <- nls(resp ~ alpha * exp(beta * trat^n) + theta*trat, start = initial) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 <- nls(ymean ~ alpha * exp(beta * xmean^n) + theta*xmean, start = initial) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*e^{%0.3e*%s}+ %s %0.3e ~~~~~ italic(R^2) == %0.2f", yname.formula, b, d, xname.formula, ifelse(e<0,"-","+"), abs(e), r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/midilli_analysis.R
#' Analysis: Modified Midilli #' #' This function performs modified Midilli regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param initial List starting estimates #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The exponential model is defined by: #' \deqn{y = \alpha \times e^{-\beta \cdot x} + \theta \cdot x} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @export #' #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' midillim(time,100-WL) midillim=function(trat, resp, initial=NA, sample.curve=1000, ylab="Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) if(is.na(initial[1])==TRUE){ theta.0 <- min(resp) * 0.5 model.0 <- lm(log(resp - theta.0) ~ trat) alpha.0 <- exp(coef(model.0)[1]) beta.0 <- coef(model.0)[2] theta.0<-theta.0/mean(trat) initial <- list(alpha = alpha.0, beta = beta.0, theta = theta.0)} model <- nls(resp ~ alpha * exp(beta * trat) + theta*trat, start = initial) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 <- nls(ymean ~ alpha * exp(beta * xmean) + theta*xmean, start = initial) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*e^{%0.3e*%s} %s %0.3e ~~~~~ italic(R^2) == %0.2f", yname.formula, b, d, xname.formula, ifelse(e<0,"-",'+'), abs(e), r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/midillim_analysis.R
#' Analysis: Mitscherlich #' #' This function performs Mitscherlich regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param initial List Initial parameters (A, b, e) #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @details #' The Mitscherlich model is defined by: #' \deqn{y = A \times (1-10^{-eb-ex})} #' #' where "y" is the yield obtained when "b" units of a nutrient are in the soil and #' "x" units of it are added as fertilizer, "A" is the maximum yield, and "e" is the #' proportionality factor, has recently received increasing interest. #' #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @export #' #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' mitscherlich(time,WL) mitscherlich=function(trat, resp, initial=NA, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) if(is.na(initial[1])==TRUE){ A=max(resp) b=0.1/max(resp) e=max(resp)/2 initial=list(A=A,b=b,e=e)} model <- nls(resp ~ A*(1-10^(-e*b-b*trat)), start = initial) coef=summary(model) if(is.na(round)==TRUE){ A=coef$coefficients[,1][1] b=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ A=round(coef$coefficients[,1][1],round) b=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1 <- nls(ymean ~ A*(1-10^(-e*b-b*xmean)), start = initial) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 eb=e*b equation=sprintf("~~~%s==%0.3e*(1-10^{%0.3e %s %0.3e*%s}) ~~~~~ italic(R^2) == %0.2f", yname.formula, A, eb, ifelse(b >= 0, "+", "-"), abs(b), xname.formula, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/mitscherlich_analysis.R
#' Analysis: Newton #' #' This function performs exponential regression analysis. This model was used by Newton. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The exponential model is defined by: #' \deqn{y = e^{-\beta \cdot x}\cdot x} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Siqueira, V. C., Resende, O., and Chaves, T. H. (2013). Mathematical modelling of the drying of jatropha fruit: an empirical comparison. Revista Ciencia Agronomica, 44, 278-285. #' @export #' #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' newton(trat,resp+0.001) newton=function(trat, resp, sample.curve=1000, ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) model.0 <- lm(log(resp) ~ trat) model <- nls(resp ~ exp(-beta * trat),start = list(beta=-coef(model.0)[2])) coef=summary(model) if(is.na(round)==TRUE){b=coef$coefficients[,1][1]} if(is.na(round)==FALSE){b=round(coef$coefficients[,1][1],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1=nls(ymean ~ exp(-beta * xmean),start = list(beta=-coef(model.0)[2])) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==e^{%s %0.3e*%s} ~~~~~ italic(R^2) == %0.2f", yname.formula, ifelse(b<=0,"","-"), abs(b), xname.formula, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/newton_analysis.R
#' @keywords internal #' @md #' @name AgroReg-package #' @docType package "_PACKAGE"
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/package.R
#' Analysis: Peleg #' #' This function performs Peleg regression analysis. #' #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param initial Starting estimates #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The Peleg model is defined by: #' \deqn{y = \frac{(1-x)}{a+bx}} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @export #' #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' peleg(time,WL) peleg=function(trat, resp, initial=NA, sample.curve=1000, ylab="Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) if(is.na(initial[1])==TRUE){ mod=lm(log(resp)~trat) a=(1-mean(trat))/(mean(resp)+coef(mod)[2]*mean(trat)) b=-coef(mod)[2] initial=list(a=a,b=b)} model <- nls(resp ~ (1-trat)/(a+b*trat), start = initial) coef=summary(model) if(is.na(round)==TRUE){ a=coef$coefficients[,1][1] b=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ a=round(coef$coefficients[,1][1],round) b=round(coef$coefficients[,1][2],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1=nls(ymean ~ (1-trat)/(a+b*xmean), start = initial) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==frac((1-%s),(%0.3e %s %0.3e*%s)) ~~~~~ italic(R^2) == %0.2f", yname.formula, xname.formula, a, ifelse(b >= 0, "+", "-"), abs(b), xname.formula, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black", family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/peleg_analysis.R
#' Merge multiple curves into a single graph #' @param plots list with objects of type analysis. #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param legend.title caption title #' @param trat name of the curves #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param legend.position legend position (\emph{default} is c(0.3,0.8)) #' @param gray gray scale (\emph{default} is FALSE) #' @param widthbar bar width (\emph{default} is 0.3) #' @param pointsize shape size #' @param linesize line size #' @param textsize Font size #' @param legendsize Legend size text #' @param legendtitlesize Title legend size #' @param fontfamily font family #' @return The function returns a graph joining the outputs of the functions LM_model, LL_model, BC_model, CD_model, loess_model, normal_model, piecewise_model and N_model #' @author Gabriel Danilo Shimizu #' @export #' @examples #' library(AgroReg) #' library(ggplot2) #' data("aristolochia") #' attach(aristolochia) #' a=LM(trat,resp) #' b=LL(trat,resp,npar = "LL.3") #' plot_arrange(list(a,b)) #' #' models <- c("LM1", "LL3") #' r <- lapply(models, function(x) { #' r <- with(granada, regression(time, WL, model = x)) #' }) #' plot_arrange(r,trat=models,ylab="WL (%)",xlab="Time (Minutes)") #' #' models = c("asymptotic_neg", "biexponential", "LL4", "BC4", "CD5", "linear.linear", #' "linear.plateau", "quadratic.plateau", "mitscherlich", "MM2") #' m = lapply(models, function(x) { #' m = with(granada, regression(time, WL, model = x))}) #' plot_arrange(m, trat = paste("(",models,")")) plot_arrange=function(plots, point="mean", theme = theme_classic(), legend.title = NULL, legend.position = "top", trat = NA, gray = FALSE, ylab = "Dependent", xlab = "Independent", widthbar = 0, pointsize = 4.5, linesize = 0.8, textsize = 12, legendsize = 12, legendtitlesize = 12, fontfamily="sans") { requireNamespace("ggplot2") equation=1:length(plots) grafico=ggplot() if(gray==FALSE & point=="mean"){ for(i in 1:length(plots)){ equation[[i]]=plots[[i]][[3]]$plot$s x=plots[[i]][[3]]$plot$temp1 y=plots[[i]][[3]]$plot$result data=data.frame(x,y,color=factor(i,unique(i))) pontosx=plots[[i]][[3]]$plot$data1$trat pontosy=plots[[i]][[3]]$plot$data1$resp desvio=plots[[i]][[3]]$plot$desvio pontos=data.frame(x=pontosx, y=pontosy, desvio=desvio, color=factor(i,unique(i))) color=pontos$color grafico=grafico+ geom_errorbar(data=pontos, aes(x=x, y=y, ymin=y-desvio, ymax=y+desvio, color=color, group=color),width=widthbar, size=linesize)+ geom_point(data=pontos,aes(x=x,y=y, color=color, group=color),size=pointsize)+ geom_line(data=data,aes(x=x, y=y, color=color, group=color),size=linesize) } texto=parse(text=paste(trat,"~",unlist(equation))) grafico=grafico+ scale_color_discrete(breaks=1:length(plots),label=texto)+ theme+labs(color=legend.title)+ylab(ylab)+xlab(xlab)+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.text = element_text(size=legendsize,family = fontfamily), legend.title = element_text(size=legendtitlesize,family = fontfamily), legend.position = legend.position, legend.justification='left', legend.direction = "vertical", legend.text.align = 0)} if(gray==TRUE & point=="mean"){ for(i in 1:length(plots)){ equation[[i]]=plots[[i]][[3]]$plot$s x=plots[[i]][[3]]$plot$temp1 y=plots[[i]][[3]]$plot$result data=data.frame(x,y,color=as.factor(i)) pontosx=plots[[i]][[3]]$plot$data1$trat pontosy=plots[[i]][[3]]$plot$data1$resp desvio=plots[[i]][[3]]$plot$desvio pontos=data.frame(x=pontosx,y=pontosy,desvio=desvio,color=as.factor(i)) grafico=grafico+ geom_errorbar(data=pontos, aes(x=x, y=y, ymin=y-desvio, ymax=y+desvio),width=widthbar, size=linesize)+ geom_point(data=pontos,aes(x=x, y=y, pch=color, group=color), size=pointsize,fill="gray")+ geom_line(data=data,aes(x=x, y=y, lty=color, group=color),size=linesize) } texto=parse(text=paste(trat,"~",unlist(equation))) grafico=grafico+ scale_linetype_discrete(label=texto,breaks=1:length(plots))+ scale_shape_discrete(label=texto,breaks=1:length(plots))+ theme+labs(lty=legend.title,shape=legend.title)+ylab(ylab)+xlab(xlab)+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=legendsize,family = fontfamily), legend.title = element_text(size=legendtitlesize,family = fontfamily), legend.justification='left', legend.direction = "vertical", legend.text.align = 0)} if(gray==FALSE & point=="all"){ for(i in 1:length(plots)){ equation[[i]]=plots[[i]][[3]]$plot$s x=plots[[i]][[3]]$plot$temp1 y=plots[[i]][[3]]$plot$result data=data.frame(x,y,color=as.factor(i)) pontosx=plots[[i]][[3]]$plot$trat pontosy=plots[[i]][[3]]$plot$resp pontos=data.frame(x=pontosx, y=pontosy, color=as.factor(i)) color=pontos$color grafico=grafico+ geom_point(data=pontos,aes(x=x,y=y, color=color, group=color),size=pointsize)+ geom_line(data=data,aes(x=x, y=y, color=color, group=color),size=linesize)} texto=parse(text=paste(trat,"~",unlist(equation))) grafico=grafico+ scale_color_discrete(label=texto,breaks=1:length(plots))+ theme+labs(color=legend.title)+ylab(ylab)+xlab(xlab)+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.text = element_text(size=legendsize,family = fontfamily), legend.title = element_text(size=legendtitlesize,family = fontfamily), legend.position = legend.position, legend.justification='left', legend.direction = "vertical", legend.text.align = 0)} if(gray==TRUE & point=="all"){ for(i in 1:length(plots)){ equation[[i]]=plots[[i]][[3]]$plot$s x=plots[[i]][[3]]$plot$temp1 y=plots[[i]][[3]]$plot$result data=data.frame(x,y,color=as.factor(i)) pontosx=plots[[i]][[3]]$plot$trat pontosy=plots[[i]][[3]]$plot$resp pontos=data.frame(x=pontosx, y=pontosy, color=as.factor(i)) grafico=grafico+ geom_point(data=pontos,aes(x=x, y=y, pch=color, group=color), size=pointsize,fill="gray")+ geom_line(data=data,aes(x=x, y=y, lty=color, group=color),size=linesize) } texto=parse(text=paste(trat,"~",unlist(equation))) grafico=grafico+ scale_linetype_discrete(label=texto,breaks=1:length(plots))+ scale_shape_discrete(label=texto,breaks=1:length(plots))+ylab(ylab)+xlab(xlab)+ theme+labs(lty=legend.title,shape=legend.title)+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.text = element_text(size=legendsize,family = fontfamily), legend.title = element_text(size=legendtitlesize,family = fontfamily), legend.position = legend.position, legend.justification='left', legend.direction = "vertical", legend.text.align = 0)} print(grafico) }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/plot_arrange.R
#' Analysis: Plateau-Linear #' #' This function performs the plateau-linear regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param round round equation #' @param colorline Color lines #' @param fillshape Fill shape #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); breakpoint and the graph using ggplot2 with the equation automatically. #' @export #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Chiu, G. S., R. Lockhart, and R. Routledge. 2006. Bent-cable regression theory and applications. Journal of the American Statistical Association 101:542-553. #' @references Toms, J. D., and M. L. Lesperance. 2003. Piecewise regression: a tool for identifying ecological thresholds. Ecology 84:2034-2041. #' @seealso \link{quadratic.plateau}, \link{linear.linear} #' @importFrom dplyr if_else #' @details #' The plateau-linear model is defined by: #' First curve: #' \deqn{y = \beta_0 + \beta_1 \times breakpoint (x < breakpoint)} #' #' Second curve: #' \deqn{y = \beta_0 + \beta_1 \times x (x > breakpoint)} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' x=time[length(time):1] #' plateau.linear(x,WL) plateau.linear=function(trat, resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, xname.formula="x", yname.formula="y", comment=NA, fontfamily="sans"){ if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} lp <- function(x, a, b, c) { if_else(condition = x < c, true = a + b * c, false = a + b * x) } data=data.frame(trat,resp) ini_fit <- lm(data = data, formula = resp ~ trat) ini_a <- ini_fit$coef[[1]] ini_b <- ini_fit$coef[[2]] ini_c <- mean(data$trat) lp_model <- nlsLM( formula = resp ~ lp(trat, a, b, c), data = data, start = list(a = ini_a, b = ini_c, c = ini_c)) model2=summary(lp_model) breakpoint=model2$coefficients[3,1] ybreakpoint=predict(lp_model,newdata = data.frame(trat=breakpoint)) m.ini <- mean(data$resp) nullfunct <- function(x, m) { m } null <- nls(resp~ nullfunct(trat, m), data = data, start = list(m = m.ini), trace = FALSE, nls.control(maxiter = 1000)) r2 <- nagelkerke(lp_model, null)$Pseudo.R.squared.for.model.vs.null[2] requireNamespace("drc") requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) r2=floor(r2*100)/100 if(is.na(round)==TRUE){ coef1=coef(model2)[1] coef2=coef(model2)[2] coef3=breakpoint} if(is.na(round)==FALSE){ coef1=round(coef(model2)[1],round) coef2=round(coef(model2)[2],round) coef3=round(breakpoint,round)} s <- sprintf("~~~%s == %e %s %e * %s ~(%s~'>'~%e) ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, xname.formula, coef3, r2) equation=s if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(lp_model) predobs=resp model=lp_model rmse=sqrt(mean((predesp-predobs)^2)) data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} xp=seq(min(trat),max(trat),length=sample.curve) yp=predict(lp_model,newdata=data.frame(trat=xp)) preditos=data.frame(x=xp,y=yp) temp1=xp result=yp x=xp y=yp graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} aic=AIC(lp_model) bic=BIC(lp_model) minimo=NA respmin=NA graphs=data.frame("Parameter"=c("Breakpoint", "Breakpoint response", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(breakpoint, ybreakpoint, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=model2, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/pltLN_analysis.R
#' @title Analysis: Plateau-quadratic #' #' @name plateau.quadratic #' @rdname plateau.quadratic #' @description This function performs the plateau-quadratic regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param width.bar Bar width #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param x Numeric vector with dependent variable. #' @param a The plateau value #' @param breakpoint breakpoint value #' @param b Linear term #' @param c Quadratic term #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The Plateau-quadratic model is defined by: #' #' First curve: #' \deqn{y = \beta_0 + \beta_1 \cdot breakpoint + \beta_2 \cdot breakpoint^2 (x < breakpoint)} #' #' Second curve: #' \deqn{y = \beta_0 + \beta_1 \cdot x + \beta_2 \cdot x^2 (x > breakpoint)} #' #' or #' #' \deqn{y = a + b(x+breakpoint) + c(x+breakpoint)^2 (x > breakpoint)} #' #' @export #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Miguez, F. (2020). nlraa: nonlinear Regression for Agricultural Applications. R package version 0.65. #' @references Chiu, G. S., R. Lockhart, and R. Routledge. 2006. Bent-cable regression theory and applications. Journal of the American Statistical Association 101:542-553. #' @references Toms, J. D., and M. L. Lesperance. 2003. Piecewise regression: a tool for identifying ecological thresholds. Ecology 84:2034-2041. #' @import minpack.lm #' @import rcompanion #' @importFrom broom tidy #' @importFrom stats nls.control #' @importFrom stats selfStart #' @importFrom stats sortedXyData #' @seealso \link{linear.linear}, \link{linear.plateau} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' x=time[length(time):1] #' plateau.quadratic(x,WL) #' @rdname plateau.quadratic #' @export plateau.quadratic=function(trat, resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ requireNamespace("minpack.lm") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("dplyr") requireNamespace("rcompanion") mod=nls(resp~plquadratic(trat,a,breakpoint,b,c)) model2=summary(mod) m.ini <- mean(resp) nullfunct <- function(x, m) { m} data=data.frame(trat,resp) null <- nls(resp~ nullfunct(trat, m), start = list(m = m.ini), trace = FALSE, data = data, nls.control(maxiter = 1000)) r2 <- nagelkerke(mod, null)$Pseudo.R.squared.for.model.vs.null[2] requireNamespace("drc") requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) r2=floor(r2*100)/100 if(is.na(round)==TRUE){ a=coef(mod)[1] breakpoint=coef(mod)[2] b=coef(mod)[3] c=coef(mod)[4]} if(is.na(round)==FALSE){ a=round(coef(mod)[1],round) breakpoint=round(coef(mod)[2],round) b=round(coef(mod)[3],round) c=round(coef(mod)[4],round)} s <- sprintf("~~~%s == %e %s %e * %s %s %e * %s^2~(%s~'>'~%e) ~~~~~ italic(R^2) == %0.2f", yname.formula, a, ifelse(b >= 0, "+", "-"), abs(b), xname.formula, ifelse(c >= 0, "+", "-"), abs(c), xname.formula, xname.formula, breakpoint, r2) equation=s if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp model=mod rmse=sqrt(mean((predesp-predobs)^2)) data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} xp=seq(min(trat),max(trat),length=sample.curve) yp=predict(mod,newdata=data.frame(trat=xp)) preditos=data.frame(x=xp,y=yp) temp1=xp result=yp x=xp y=yp graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} aic=AIC(model) bic=BIC(model) minimo=NA respmin=NA ybreakpoint=predict(mod,newdata = data.frame(trat=breakpoint)) graphs=data.frame("Parameter"=c("Breakpoint", "Breakpoint response", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(breakpoint, ybreakpoint, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=model2, "values"=graphs, "plot"=graph) graficos } pquadInit <- function(mCall, LHS, data, ...){ xy <- sortedXyData(mCall[["x"]], LHS, data) if(nrow(xy) < 4){ stop("Small sample size")} xy1 <- xy[1:floor(nrow(xy)/2),] xy2 <- xy[floor(nrow(xy)/2):nrow(xy),] xy2$x2 <- xy2[,"x"] - min(xy2[,"x"]) fit2 <- stats::lm(xy2[,"y"] ~ xy2[,"x2"] + I(xy2[,"x2"]^2)) a <- coef(fit2)[1] b <- coef(fit2)[2] c <- coef(fit2)[3] objfun <- function(cfs){ pred <- pquad(xy[,"x"], a=cfs[1], breakpoint=cfs[2], b=cfs[3], c=cfs[4]) ans <- sum((xy[,"y"] - pred)^2) ans} op <- try(stats::optim(c(a, mean(xy[,"x"]),b,c), objfun, method = "L-BFGS-B", upper = c(Inf, max(xy[,"x"]), Inf, Inf), lower = c(-Inf, min(xy[,"x"]), -Inf, -Inf)), silent = TRUE) if(op[1] != "try-error"){ a <- op$par[1] breakpoint <- op$par[2] b <- op$par[3] c <- op$par[4]}else{ a <- mean(xy1[,"y"]) breakpoint <- mean(xy[,"x"]) b <- b c <- c} value <- c(a, breakpoint, b, c) names(value) <- mCall[c("a","breakpoint","b","c")] value} pquad <- function(x, a, breakpoint, b, c){ .value <- (x < breakpoint) * a + (x >= breakpoint) * (a + b * (x - breakpoint) + c * (x - breakpoint)^2) .exp1 <- 1 .exp2 <- ifelse(x < breakpoint, 0, -b + -(c * (2 * (x - breakpoint)))) .exp3 <- ifelse(x < breakpoint, 0, x - breakpoint) .exp4 <- ifelse(x < breakpoint, 0, (x - breakpoint)^2) .actualArgs <- as.list(match.call()[c("a","breakpoint","b","c")]) if (all(unlist(lapply(.actualArgs, is.name)))) { .grad <- array(0, c(length(.value), 4L), list(NULL, c("a","breakpoint","b","c"))) .grad[, "a"] <- .exp1 .grad[, "breakpoint"] <- .exp2 .grad[, "b"] <- .exp3 .grad[, "c"] <- .exp4 dimnames(.grad) <- list(NULL, .actualArgs) attr(.value, "gradient") <- .grad} .value} #' @rdname plateau.quadratic #' @export plquadratic <- selfStart(model = pquad, initial = pquadInit, parameters = c("a","breakpoint","b","c"))
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/pltQD_analysis.R
#' Analysis: Potencial #' #' This function performs potencial regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Siqueira, V. C., Resende, O., & Chaves, T. H. (2013). Mathematical modelling of the drying of jatropha fruit: an empirical comparison. Revista Ciencia Agronomica, 44, 278-285. #' @export #' @details #' The exponential model is defined by: #' \deqn{y = \alpha \times trat^{\beta}} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' potential(time,WL) potential=function(trat, resp, sample.curve=1000, ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, yname.formula = "y", xname.formula = "x", comment = NA, fontfamily="sans"){ requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) data=data.frame(trat,resp) mod=lm(log(resp)~log(trat)) model=nls(resp~A*trat^B,start = list(A=exp(coef(mod)[1]), B=coef(mod)[2])) coef=summary(model) if(is.na(round)==TRUE){ A=coef$coefficients[,1][1] B=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ A=round(coef$coefficients[,1][1],round) B=round(coef$coefficients[,1][2],round)} if(r2=="all"){r2=1-deviance(model)/deviance(lm(resp~1))} if(r2=="mean"){ model1=nls(ymean~A*xmean^B,start = list(A=exp(coef(mod)[1]), B=coef(mod)[2])) r2=1-deviance(model1)/deviance(lm(ymean~1))} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*%s^{%0.3e} ~~~~~ italic(R^2) == %0.2f", yname.formula, A, xname.formula, B, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/potential_analysis.R
#' Analysis: Quadratic-plateau #' #' This function performs the quadratic-plateau regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param width.bar Bar width #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The quadratic-plateau model is defined by: #' #' First curve: #' \deqn{y = \beta_0 + \beta_1 \cdot x + \beta_2 \cdot x^2 (x < breakpoint)} #' #' Second curve: #' \deqn{y = \beta_0 + \beta_1 \cdot breakpoint + \beta_2 \cdot breakpoint^2 (x > breakpoint)} #' @export #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Chiu, G. S., R. Lockhart, and R. Routledge. 2006. Bent-cable regression theory and applications. Journal of the American Statistical Association 101:542-553. #' @references Toms, J. D., and M. L. Lesperance. 2003. Piecewise regression: a tool for identifying ecological thresholds. Ecology 84:2034-2041. #' @import minpack.lm #' @import rcompanion #' @importFrom broom tidy #' @importFrom stats nls.control #' @seealso \link{linear.linear}, \link{linear.plateau} #' @examples #' library(AgroReg) #' data("granada") #' attach(granada) #' quadratic.plateau(time,WL) quadratic.plateau=function(trat,resp, sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", error="SE", r2="all", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ requireNamespace("minpack.lm") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("dplyr") requireNamespace("rcompanion") qp <- function(x, b0, b1, b2) { jp <- -0.5 * b1 / b2 if_else( condition = x < jp, true = b0 + (b1 * x) + (b2 * x * x), false = b0 + (b1 * jp) + (b2 * jp * jp) ) } qp_jp <- function(x, b0, b1, jp) { b2 <- -0.5 * b1 / jp if_else( condition = x < jp, true = b0 + (b1 * x) + (b2 * x * x), false = b0 + (b1 * jp) + (b2 * jp * jp) ) } data=data.frame(trat,resp) start <- lm(resp ~ poly(trat, 2, raw = TRUE), data = data) start_b0 <- start$coef[[1]] start_b1 <- start$coef[[2]] start_b2 <- start$coef[[3]] start_jp <- mean(data$resp) try(corr_model <- minpack.lm::nlsLM( formula = resp ~ qp(trat, b0, b1, b2), data = data, start = list(b0 = start_b0, b1 = start_b1, b2 = start_b2) )) model1=summary(corr_model) try(corr_model_jp <- minpack.lm::nlsLM( formula = resp ~ qp_jp(trat, b0, b1, jp), data = data, start = list(b0 = start_b0, b1 = start_b1, jp = start_jp))) model2=summary(corr_model_jp) breakpoint=model2$coefficients[3,1] ybreakpoint=predict(corr_model,newdata = data.frame(trat=breakpoint)) nullfunct <- function(x, m) { m } m_ini <- mean(data$resp) null <- nls(resp ~ nullfunct(trat, m), data = data, start = list(m = m_ini), trace = FALSE) model_error <- round(summary(corr_model)$sigma, 2) r2 <- rcompanion::nagelkerke(corr_model, null)$Pseudo.R.squared.for.model.vs.null[2] b0 <- tidy(corr_model)$estimate[1] b1 <- tidy(corr_model)$estimate[2] b2 <- tidy(corr_model)$estimate[3] cc <- tidy(corr_model_jp)$estimate[3] plateau <- round(b0 + (b1 * cc) + (b2 * cc * cc), 1) requireNamespace("drc") requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) r2=floor(r2*100)/100 if(is.na(round)==TRUE){ coef1=coef(model1)[1] coef2=coef(model1)[2] coef3=coef(model1)[3] coef4=breakpoint} if(is.na(round)==FALSE){ coef1=round(coef(model1)[1],round) coef2=round(coef(model1)[2],round) coef3=round(coef(model1)[3],round) coef4=round(breakpoint,round)} s <- sprintf("~~~%s == %e %s %e * %s %s %e * %s^2~(%s~'<'~%e) ~~~~~ italic(R^2) == %0.2f", yname.formula, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.formula, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.formula, xname.formula, coef4, r2) equation=s if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(corr_model) predobs=resp model=corr_model rmse=sqrt(mean((predesp-predobs)^2)) data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} xp=seq(min(trat),max(trat),length=sample.curve) yp=predict(corr_model,newdata=data.frame(trat=xp)) preditos=data.frame(x=xp,y=yp) temp1=xp result=yp x=xp y=yp graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} minimo=NA respmin=NA aic=AIC(corr_model_jp) bic=BIC(corr_model_jp) graphs=data.frame("Parameter"=c("Breakpoint", "Breakpoint Response", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(breakpoint, ybreakpoint, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients quadratic model"=model1, "Coefficients segmented"=model2, "plot"=graph, "values"=graphs) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/quadraticplateau_analysis.R
#' Analysis: Regression linear or nonlinear #' #' @description This function is a simplification of all the analysis functions present in the package. #' @export #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param model model regression (\emph{default} is LM1) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param legend.position legend position (\emph{default} is c(0.3,0.8)) #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param pointshape format point (default is 21) #' @param round round equation #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param fontfamily Font family #' @details To change the regression model, change the "model" argument to: #' #' 1. **N:** Graph for not significant trend. #' 2. **loess0:** Loess non-parametric degree 0 #' 3. **loess1:** Loess non-parametric degree 1 #' 4. **loess2:** Loess non-parametric degree 2 #' 5. **LM0.5:** Quadratic inverse #' 6. **LM1:** Linear regression. #' 7. **LM2:** Quadratic #' 8. **LM3:** Cubic #' 9. **LM4:** Quartic #' 10. **LM0.5_i:** Quadratic inverse without intercept. #' 11. **LM1_i:** Linear without intercept. #' 12. **LM2_i:** Quadratic regression without intercept. #' 13. **LM3_i:** Cubic without intercept. #' 14. **LM4_i:** Quartic without intercept. #' 15. **LM13:** Cubic without beta2 #' 16. **LM13i:** Cubic inverse without beta2 #' 17. **LM23:** Cubic without beta1 #' 18. **LM23i:** Cubic inverse without beta2 #' 19. **LM2i3:** Cubic without beta1, with inverse beta3 #' 20. **valcam:** Valcam #' 21. **L3:** Three-parameter logistics. #' 22. **L4:** Four-parameter logistics. #' 23. **L5:** Five-parameter logistics. #' 24. **LL3:** Three-parameter log-logistics. #' 25. **LL4:** Four-parameter log-logistics. #' 26. **LL5:** Five-parameter log-logistics. #' 27. **BC4:** Brain-Cousens with four parameter. #' 28. **BC5:** Brain-Cousens with five parameter. #' 29. **CD4:** Cedergreen-Ritz-Streibig with four parameter. #' 30. **CD5:** Cedergreen-Ritz-Streibig with five parameter. #' 31. **weibull3:** Weibull with three parameter. #' 32. **weibull4:** Weibull with four parameter. #' 33. **GP2:** Gompertz with two parameter. #' 34. **GP3:** Gompertz with three parameter. #' 35. **GP4:** Gompertz with four parameter. #' 36. **VB:** Von Bertalanffy #' 37. **lo3:** Lorentz with three parameter #' 38. **lo4:** Lorentz with four parameter #' 39. **beta:** Beta #' 40. **gaussian3:** Analogous to the Gaussian model/Bragg with three parameters. #' 41. **gaussian4:** Analogous to the Gaussian model/Bragg with four parameters. #' 42. **linear.linear:** Linear-linear #' 43. **linear.plateau:** Linear-plateau #' 44. **quadratic.plateau:** Quadratic-plateau #' 45. **plateau.linear:** Plateau-linear #' 46. **plateau.quadratic:** Plateau-Quadratic #' 47. **log:** Logarithmic #' 48. **log2:** Logarithmic quadratic #' 49. **thompson:** Thompson #' 50. **asymptotic:** Exponential #' 51. **asymptotic_neg:** Exponential negative #' 52. **asymptotic_i:** Exponential without intercept. #' 53. **asymptotic_ineg:** Exponential negative without intercept. #' 54. **biexponential:** Biexponential #' 55. **mitscherlich:** Mitscherlich #' 56. **yieldloss:** Yield-loss #' 57. **hill:** Hill #' 58. **MM2:** Michaelis-Menten with two parameter. #' 59. **MM3:** Michaelis-Menten with three parameter. #' 60. **SH:** Steinhart-Hart #' 61. **page:** Page #' 62. **newton:** Newton #' 63. **potential:** Potential #' 64. **midilli:** Midilli #' 65. **midillim:** Modified Midilli #' 66. **AM:** Avhad and Marchetti #' 67. **peleg:** Peleg #' 68. **VG:** Vega-Galvez # #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @md #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' regression(trat, resp) regression=function(trat, resp, model="LM1", ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", point="all", textsize = 12, pointsize = 4.5, linesize = 0.8, pointshape = 21, round=NA, fontfamily="sans", error = "SE", width.bar=NA, xname.formula = "x", yname.formula = "y"){ if(model=="N"){a=Nreg(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,fontfamily = fontfamily,error = error)} if(model=="LM0.5"){a=LM(trat, resp, degree=0.5, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM1"){a=LM(trat, resp, degree=1, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM2"){a=LM(trat, resp, degree=2, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM3"){a=LM(trat, resp, degree=3, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM4"){a=LM(trat, resp, degree=4, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM0.5_i"){a=LM_i(trat, resp, degree=0.5, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM1_i"){a=LM_i(trat, resp, degree=1, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM2_i"){a=LM_i(trat, resp, degree=2, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM3_i"){a=LM_i(trat, resp, degree=3, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM4_i"){a=LM_i(trat, resp, degree=4, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM13"){a=LM13(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM13i"){a=LM13i(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM23"){a=LM23(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM23i"){a=LM23i(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LM2i3"){a=LM2i3(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="L3"){a=logistic(trat, resp, npar="L.3", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="L4"){a=logistic(trat, resp, npar="L.4", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="L5"){a=logistic(trat, resp, npar="L.5", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LL3"){a=LL(trat, resp, npar="LL.3", ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LL4"){a=LL(trat, resp, npar="LL.4", ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="LL5"){a=LL(trat, resp, npar="LL.5", ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="BC4"){a=BC(trat, resp, npar="BC.4", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="BC5"){a=BC(trat, resp, npar="BC.5", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="CD4"){a=CD(trat, resp, npar="CRS.4", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="CD5"){a=CD(trat, resp, npar="CRS.5", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="weibull3"){a=weibull(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="weibull4"){a=weibull(trat, resp, npar="w4",ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="GP2"){a=GP(trat, resp, npar = "g2", ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="GP3"){a=GP(trat, resp, npar = "g3", ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="GP4"){a=GP(trat, resp, npar = "g4", ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="lo3"){a=lorentz(trat, resp, npar = "lo3", ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="lo4"){a=lorentz(trat, resp, npar = "lo4", ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="beta"){a=beta_reg(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="gaussian3"){a=gaussianreg(trat, resp, npar="g3", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="gaussia4"){a=gaussianreg(trat, resp,npar = "g4", ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="linear.linear"){a=linear.linear(trat, resp, ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="linear.plateau"){a=linear.plateau(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="quadratic.plateau"){a=quadratic.plateau(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="plateau.linear"){a=plateau.linear(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="plateau.quadratic"){a=plateau.quadratic(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="log"){a=LOG(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="log2"){a=LOG2(trat, resp, ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="thompson"){a=thompson(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="asymptotic"){a=asymptotic(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="asymptotic_neg"){a=asymptotic_neg(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="asymptotic_i"){a=asymptotic_i(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="asymptotic_ineg"){a=asymptotic_ineg(trat, resp, ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="biexponential"){a=biexponential(trat, resp,ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="mitscherlich"){a=mitscherlich(trat, resp, ylab=ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="MM2"){a=MM(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="MM3"){a=MM(trat, resp, npar="mm3",ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="loess0"){a=loessreg(trat, resp, degree = 0, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,fontfamily = fontfamily,error = error)} if(model=="loess1"){a=loessreg(trat, resp, degree = 1, ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,fontfamily = fontfamily,error = error)} if(model=="loess2"){a=loessreg(trat, resp, degree = 2, ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,fontfamily = fontfamily,error = error)} if(model=="SH"){a=SH(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="page"){a=PAGE(trat, resp, ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="newton"){a=newton(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="valcam"){a=valcam(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="potential"){a=potential(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="midilli"){a=midilli(trat, resp, ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="midillim"){a=midillim(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="hill"){a=hill(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="AM"){a=AM(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="yieldloss"){a=yieldloss(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="VB"){a=VB(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="peleg"){a=peleg(trat, resp, ylab = ylab, xlab = xlab, theme = theme, legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} if(model=="VG"){a=VG(trat, resp, ylab = ylab, xlab = xlab, theme = theme,legend.position = legend.position,point = point,width.bar = width.bar,textsize = textsize, pointsize = pointsize,linesize = linesize,pointshape = pointshape,round = round,fontfamily = fontfamily,error = error,xname.formula = xname.formula,yname.formula = yname.formula)} a }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/regression.R
#' Analysis: Other statistical parameters #' #' This function calculates other statistical parameters such as Mean (Bias) Error, Relative Mean (Bias) Error, Mean Absolute Error, Relative Mean Absolute Error, Root Mean Square Error, Relative Root Mean Square Error, Modeling Efficiency, Standard deviation of differences, Coefficient of Residual Mass. #' @param models List with objects of type analysis #' @param names_model Names of the models #' @param round Round numbers #' @return Returns a table with the statistical parameters for choosing the model. #' @author Gabriel Danilo Shimizu #' @export #' @examples #' library(AgroReg) #' data(granada) #' attach(granada) #' a=LM(time,WL) #' b=LL(time,WL) #' c=BC(time,WL) #' d=weibull(time,WL) #' stat_param(models=list(a,b,c,d)) stat_param<-function(models, names_model=NA, round=3){ mbe=c() rmbe=c() mae=c() rmae=c() se=c() mse=c() rmse=c() rrmse=c() me=c() sd=c() crm=c() AC=c() ACU=c() ACs=c() for(i in 1:length(models)){ mod=models[[i]][[3]]$plot$model resp=models[[i]][[3]]$plot$resp mbe[i]=mean((predict(mod)-resp)) rmbe[i]=mean((predict(mod)-resp))/mean(resp)*100 mae[i]=1/length(resp)*sum(abs(predict(mod)-resp)) rmae[i]=(1/length(resp)*sum(abs(predict(mod)-resp)))/mean(resp)*100 se[i]=sum((predict(mod)-resp)^2) mse[i]=se[i]/length(resp) rmse[i]=sqrt(mse[i]) rrmse[i]=rmse[i]/mean(resp)*100 me[i]=1 - (sum((predict(mod)-resp)^2)/sum((resp - mean(resp))^2)) sd[i]=sd(predict(mod)-resp) crm[i] <- (mean(resp - predict(mod), na.rm = T))/mean(resp) respe=predict(mod) dif <- respe-resp mdif <- mean(dif, na.rm = T) sdif <- dif^2 msdif <- mean(sdif, na.rm = T) mmea <- mean(resp, na.rm = T) mcal <- mean(respe, na.rm = T) SSD <- sum(sdif) SPOD <- sum((abs(mcal-mmea)+abs(respe-mcal))*(abs(mcal-mmea)+abs(resp-mmea))) b <- sqrt((sum((resp - mean(resp))^2))/(sum((respe - mean(respe))^2))) if(!is.na(cor(respe,resp)) & cor(respe, resp) < 0){b <- -b} a <- mmea - b * mcal dY <- a + b * respe dX <- -a/b + (1/b) * resp SPDu <- sum((abs(respe - dX)) * (abs(resp - dY))) SPDs <- SSD - SPDu AC[i] <- 1 - (SSD/SPOD) ACU[i] <- 1 - (SPDu/SPOD) ACs[i] <- 1 - (SPDs/SPOD)} tabela=rbind(round(mbe,round), round(rmbe,round), round(mae,round), round(rmae,round), round(se,round), round(mse,round), round(rmse,round), round(rrmse,round), round(me,round), round(sd,round), round(crm,round), round(AC,round), round(ACU,round), round(ACs,round)) if(is.na(names_model[1])==TRUE){colnames(tabela)=paste("Model",1:length(models))} rownames(tabela)=c("Mean Bias Error", "Relative Mean Bias Error", "Mean Absolute Error", "Relative Mean Absolute Error", "Squared error", "Mean squared error", "Root Mean Square Error", "Relative Root Mean Square Error", "Modelling Efficiency", "Standard deviation of differences", "Coefficient of Residual Mass", "Agreement Coefficient", "Unsystematic Agreement Coefficient", "Systematic Agreement Coefficient") tabela}
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/stat_param.R
#' Analysis: Thompson #' #' @description This function performs Thompson regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is c(0.3,0.8)) #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details #' The logarithmic model is defined by: #' \deqn{y = \beta_1 ln(\cdot x) + \beta_2 ln(\cdot x)^2} #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Sadeghi, E., Haghighi Asl, A., & Movagharnejad, K. (2019). Mathematical modelling of infrared-dried kiwifruit slices under natural and forced convection. Food science & nutrition, 7(11), 3589-3606. #' @export #' #' @examples #' library(AgroReg) #' resp=c(10,8,6.8,6,5,4.3,4.1,4.2,4.1) #' trat=seq(1,9,1) #' thompson(trat,resp) thompson = function(trat, resp, sample.curve=1000, ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", error = "SE", r2 = "all", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, yname.formula="y", xname.formula="x", comment = NA, fontfamily="sans") { requireNamespace("drc") requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) model <- lm(resp ~ log(trat)+I(log(trat)^2)-1) model1<- lm(ymean ~ log(xmean)+I(log(xmean)^2)-1) coef=summary(model) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round)} if(r2=="all"){r2=coef$r.squared} if(r2=="mean"){ coef1=summary(model1) r2=coef1$r.squared} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e*ln(%s) %s %0.3e*ln(%s)^2 ~~~~~ italic(R^2) == %0.2f", yname.formula, d, xname.formula, ifelse(b<0,"-","+"), abs(b), xname.formula, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/thompson_analysis.R
#' Analysis: Valcam #' #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @description This function performs Valcam regression analysis. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Dependent variable name (Accepts the \emph{expression}() function) #' @param xlab Independent variable name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_classic()) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param legend.position legend position (\emph{default} is "top") #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param fontfamily Font family #' #' @details #' The Valcam model is defined by: #' \deqn{y = \beta_0 + \beta_1\cdot x + \beta_2\cdot x^1.5 + \beta_3\cdot x^2} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @references Siqueira, V. C., Resende, O., & Chaves, T. H. (2013). Mathematical modelling of the drying of jatropha fruit: an empirical comparison. Revista Ciencia Agronomica, 44, 278-285. #' @export #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' valcam(trat,resp) valcam=function(trat, resp, sample.curve=1000, error = "SE", ylab = "Dependent", xlab = "Independent", theme = theme_classic(), legend.position = "top", r2 = "mean", point = "all", width.bar = NA, scale = "none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round = NA, yname.formula="y", xname.formula="x", comment = NA, fontfamily="sans") { if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} requireNamespace("ggplot2") ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} desvio=ysd xmean=tapply(trat,trat,mean) theta.0 <- min(resp) * 0.5 model <- lm(resp ~ trat+I(trat^1.5)+I(trat^2)) coef=summary(model) if(is.na(round)==TRUE){ a=coef$coefficients[,1][1] b=coef$coefficients[,1][2] c=coef$coefficients[,1][3] d=coef$coefficients[,1][4]} if(is.na(round)==FALSE){ a=round(coef$coefficients[,1][1],round) b=round(coef$coefficients[,1][2],round) c=round(coef$coefficients[,1][3],round) d=round(coef$coefficients[,1][4],round)} modm=lm(ymean~xmean+I(xmean^1.5)+I(xmean^2)) if(r2=="all"){r2=round(summary(model)$r.squared,2)} if(r2=="mean"){r2=round(summary(modm)$r.squared,2)} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %e %s %e * %s %s %e * %s^1.5 %s %0.e * %s^2 ~~~~~ italic(R^2) == %0.2f", yname.formula, coef(modm)[1], ifelse(coef(modm)[2] >= 0, "+", "-"), abs(coef(modm)[2]), xname.formula, ifelse(coef(modm)[3] >= 0, "+", "-"), abs(coef(modm)[3]), xname.formula, ifelse(coef(modm)[4] >= 0, "+", "-"), abs(coef(modm)[4]), xname.formula, r2) if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(model,newdata = data.frame(trat=xp))) predesp=predict(model) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+geom_line(data=preditos,aes(x=x, y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(model,newdata = data.frame(trat=temp1),type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(model) bic=BIC(model) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/valcam_analysis.R
#' Analysis: Weibull #' #' @description The w3' and 'w4' logistical models provide Weibull. This model was extracted from the 'drc' package. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param npar Number of model parameters (\emph{default} is w3) #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab Treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position Legend position (\emph{default} is "top") #' @param r2 Coefficient of determination of the mean or all values (\emph{default} is all) #' @param ic Add interval of confidence #' @param fill.ic Color interval of confidence #' @param alpha.ic confidence interval transparency level #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point Defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize Shape size #' @param linesize Line size #' @param linetype line type #' @param pointshape Format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @details The three-parameter Weibull model is given by the expression #' \deqn{y = d\exp(-\exp(b(\log(x)-e)))} #' Fixing the lower limit at 0 yields the four-parameter model #' \deqn{y = c + (d-c) (1 - \exp(-\exp(b(\log(x)-\log(e)))))} #' @export #' @author Model imported from the drc package (Ritz et al., 2016) #' @author Gabriel Danilo Shimizu #' @author Leandro Simoes Azeredo Goncalves #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Ritz, C.; Strebig, J.C. and Ritz, M.C. Package ‘drc’. Creative Commons: Mountain View, CA, USA, 2016. #' @seealso \link{LL}, \link{CD},\link{GP} #' @examples #' library(AgroReg) #' data("aristolochia") #' attach(aristolochia) #' weibull(trat,resp) weibull=function(trat, resp, npar="w3", sample.curve=1000, ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", r2="all", ic=FALSE, fill.ic="gray70", alpha.ic=0.5, error="SE", point="all", width.bar=NA, scale="none", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") ymean=tapply(resp,trat,mean) if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd if(npar=="w3"){mod=drm(resp~trat,fct=w3()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] d=coef$coefficients[,1][2] e=coef$coefficients[,1][3]} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) d=round(coef$coefficients[,1][2],round) e=round(coef$coefficients[,1][3],round)} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s==%0.3e * e^{-e^{%0.3e*(log(%s)-log(%0.3e))}} ~~~~~ italic(R^2) == %0.2f", yname.formula, d, b, xname.formula, e, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) } if(npar=="w4"){mod=drm(resp~trat,fct=w4()) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] d=coef$coefficients[,1][3] e=coef$coefficients[,1][4] cd=d-c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) d=round(coef$coefficients[,1][3],round) e=round(coef$coefficients[,1][4],round) cd=d-c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s == %0.3e %s %0.3e * e^{-e^{%0.3e*(log(%s)-log(%0.3e))}} ~~~~~ italic(R^2) == %0.2f", yname.formula, c, ifelse(cd<0,"-","+"), abs(cd), b, xname.formula, e, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp)))} if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) x=preditos$x y=preditos$y s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+ geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd),size=linesize, width=width.bar)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(ic==TRUE){ pred=data.frame(x=xp, y=predict(mod,interval = "confidence",newdata = data.frame(trat=xp))) preditosic=data.frame(x=c(pred$x,pred$x[length(pred$x):1]), y=c(pred$y.Lower,pred$y.Upper[length(pred$x):1])) graph=graph+geom_polygon(data=preditosic,aes(x=x,y),fill=fill.ic,alpha=alpha.ic)} graph=graph+theme+ geom_line(data=preditos,aes(x=x, y=y, color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1), type="response") maximo=temp1[which.max(result)] respmax=result[which.max(result)] minimo=temp1[which.min(result)] respmin=result[which.min(result)] aic=AIC(mod) bic=BIC(mod) graphs=data.frame("Parameter"=c("X Maximum", "Y Maximum", "X Minimum", "Y Minimum", "AIC", "BIC", "r-squared", "RMSE"), "values"=c(maximo, respmax, minimo, respmin, aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/weibull_analysis.R
#' Analysis: Yield-loss #' #' This function performs regression analysis using the Yield loss model. #' @param trat Numeric vector with dependent variable. #' @param resp Numeric vector with independent variable. #' @param sample.curve Provide the number of observations to simulate curvature (default is 1000) #' @param ylab Variable response name (Accepts the \emph{expression}() function) #' @param xlab treatments name (Accepts the \emph{expression}() function) #' @param theme ggplot2 theme (\emph{default} is theme_bw()) #' @param legend.position legend position (\emph{default} is "top") #' @param error Error bar (It can be SE - \emph{default}, SD or FALSE) #' @param r2 coefficient of determination of the mean or all values (\emph{default} is all) #' @param scale Sets x scale (\emph{default} is none, can be "log") #' @param point defines whether you want to plot all points ("all") or only the mean ("mean") #' @param width.bar Bar width #' @param textsize Font size #' @param pointsize shape size #' @param linesize line size #' @param linetype line type #' @param pointshape format point (default is 21) #' @param colorline Color lines #' @param fillshape Fill shape #' @param round round equation #' @param xname.formula Name of x in the equation #' @param yname.formula Name of y in the equation #' @param comment Add text after equation #' @param fontfamily Font family #' @details #' The Yield Loss model is defined by: #' \deqn{y = \frac{i \times x}{1+\frac{i}{A} \times x}} #' @return The function returns a list containing the coefficients and their respective values of p; statistical parameters such as AIC, BIC, pseudo-R2, RMSE (root mean square error); largest and smallest estimated value and the graph using ggplot2 with the equation automatically. #' @export #' @author Model imported from the aomisc package (Onofri, 2020) #' @author Gabriel Danilo Shimizu #' @references Seber, G. A. F. and Wild, C. J (1989) Nonlinear Regression, New York: Wiley & Sons (p. 330). #' @references Onofri A. (2020) The broken bridge between biologists and statisticians: a blog and R package, Statforbiology, IT, web: https://www.statforbiology.com #' @examples #' data("granada") #' attach(granada) #' yieldloss(time,WL) #' @md yieldloss=function(trat, resp, sample.curve=1000, error="SE", ylab="Dependent", xlab="Independent", theme=theme_classic(), legend.position="top", point="all", width.bar=NA, r2="all", textsize = 12, pointsize = 4.5, linesize = 0.8, linetype=1, pointshape = 21, fillshape = "gray", colorline = "black", round=NA, yname.formula="y", xname.formula="x", comment=NA, scale="none", fontfamily="sans"){ requireNamespace("ggplot2") requireNamespace("drc") if(is.na(width.bar)==TRUE){width.bar=0.01*mean(trat)} ymean=tapply(resp,trat,mean) if(error=="SE"){ysd=tapply(resp,trat,sd)/sqrt(tapply(resp,trat,length))} if(error=="SD"){ysd=tapply(resp,trat,sd)} if(error=="FALSE"){ysd=0} xmean=tapply(trat,trat,mean) desvio=ysd DRC.YL <- function(fixed = c(NA, NA), names = c("i", "A")) { YL.fun <- function(predictor, i, A) { i * predictor/(1 + i/A * predictor)} numParm <- 2 if (!is.character(names) | !(length(names) == numParm)) {stop("Not correct 'names' argument")} if (!(length(fixed) == numParm)) {stop("Not correct 'fixed' argument")} notFixed <- is.na(fixed) parmVec <- rep(0, numParm) parmVec[!notFixed] <- fixed[!notFixed] fct <- function(x, parm) { parmMat <- matrix(parmVec, nrow(parm), numParm, byrow = TRUE) parmMat[, notFixed] <- parm i <- parmMat[, 1]; A <- parmMat[, 2] YL.fun(x, i, A)} ssfct <- function(dataf) { x <- dataf[, 1] y <- dataf[, 2] pseudoY <- 1 / y[x > 0] pseudoX <- 1 / x [x > 0] coefs <- coef( lm(pseudoY ~ pseudoX) ) A <- 1 / coefs[1]; i <- 1 / coefs[2] return(c(i, A)[notFixed])} pnames <- names[notFixed] text <- "Yield-Loss function (Cousens, 1985)" returnList <- list(fct = fct, ssfct = ssfct, names = pnames, text = text, noParm = sum(is.na(fixed))) class(returnList) <- "drcMean" invisible(returnList)} mod=drm(resp~trat,fct=DRC.YL()) mod=nls(resp~i * trat/(1 + i/A * trat), start = list(i=coef(mod)[1], A=coef(mod)[2])) model=mod coef=summary(mod) if(is.na(round)==TRUE){ b=coef$coefficients[,1][1] c=coef$coefficients[,1][2] bc=b/c} if(is.na(round)==FALSE){ b=round(coef$coefficients[,1][1],round) c=round(coef$coefficients[,1][2],round) bc=b/c} if(r2=="all"){r2=cor(resp, fitted(mod))^2} if(r2=="mean"){r2=cor(ymean, predict(mod,newdata=data.frame(trat=unique(trat))))^2} r2=floor(r2*100)/100 equation=sprintf("~~~%s== frac(%0.3e * %s, 1 %s %0.3e * %s) ~~~~~ italic(R^2) == %0.2f", yname.formula, b, xname.formula, ifelse(bc <= 0, "-","+"), bc, xname.formula, r2) xp=seq(min(trat),max(trat),length.out = sample.curve) preditos=data.frame(x=xp, y=predict(mod,newdata = data.frame(trat=xp))) x=preditos$x y=preditos$y if(is.na(comment)==FALSE){equation=paste(equation,"~\"",comment,"\"")} s=equation data=data.frame(xmean,ymean) data1=data.frame(trat=xmean,resp=ymean) if(point=="mean"){ graph=ggplot(data,aes(x=xmean,y=ymean)) if(error!="FALSE"){graph=graph+geom_errorbar(aes(ymin=ymean-ysd,ymax=ymean+ysd), width=width.bar, size=linesize)} graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} if(point=="all"){ graph=ggplot(data.frame(trat,resp),aes(x=trat,y=resp)) graph=graph+ geom_point(aes(color="black"),size=pointsize,shape=pointshape,fill=fillshape)} graph=graph+theme+ geom_line(data=preditos,aes(x=x,y=y,color="black"),size=linesize,lty=linetype)+ scale_color_manual(name="",values=colorline,label=parse(text = equation))+ theme(axis.text = element_text(size=textsize,color="black",family = fontfamily), axis.title = element_text(size=textsize,color="black",family = fontfamily), legend.position = legend.position, legend.text = element_text(size=textsize,family = fontfamily), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0)+ ylab(ylab)+xlab(xlab) if(scale=="log"){graph=graph+scale_x_log10()} temp1=seq(min(trat),max(trat),length.out=sample.curve) result=predict(mod,newdata = data.frame(trat=temp1),type="response") aic=AIC(mod) bic=BIC(mod) predesp=predict(mod) predobs=resp rmse=sqrt(mean((predesp-predobs)^2)) graphs=data.frame("Parameter"=c("AIC", "BIC", "r-squared", "RMSE"), "values"=c(aic, bic, r2, rmse)) graficos=list("Coefficients"=coef, "values"=graphs, "plot"=graph) graficos }
/scratch/gouwar.j/cran-all/cranData/AgroReg/R/yieldloss_analysis.R
dbc.analysis=function(trat, block, response, norm="sw", homog="bt", alpha.f=0.05, alpha.t=0.05, quali=TRUE, mcomp="tukey", grau=1, transf=1, constant=0, test="parametric", geom="bar", theme=theme_classic(), sup=NA, CV=TRUE, ylab="response", xlab="", textsize=12, labelsize=4, fill="lightblue", angle=0, family="sans", dec=3, addmean=TRUE, errorbar=TRUE, posi="top", point="mean_sd", angle.label=0){ mean.stat <-function (y, x, stat = "mean"){ k<-0 numerico<- NULL if(is.null(ncol(x))){ if(is.numeric(x)){ k<-1 numerico[1]<-1}} else{ ncolx<-ncol(x) for (i in 1:ncolx) { if(is.numeric(x[,i])){ k<-k+1 numerico[k]<-i }}} cx <- deparse(substitute(x)) cy <- deparse(substitute(y)) x <- data.frame(c1 = 1, x) y <- data.frame(v1 = 1, y) nx <- ncol(x) ny <- ncol(y) namex <- names(x) namey <- names(y) if (nx == 2) namex <- c("c1", cx) if (ny == 2) namey <- c("v1", cy) namexy <- c(namex, namey) for (i in 1:nx) { x[, i] <- as.character(x[, i])} z <- NULL for (i in 1:nx){z <- paste(z, x[, i], sep = "&")} w <- NULL for (i in 1:ny) { m <- tapply(y[, i], z, stat) m <- as.matrix(m) w <- cbind(w, m)} nw <- nrow(w) c <- rownames(w) v <- rep("", nw * nx) dim(v) <- c(nw, nx) for (i in 1:nw) { for (j in 1:nx) { v[i, j] <- strsplit(c[i], "&")[[1]][j + 1]}} rownames(w) <- NULL junto <- data.frame(v[, -1], w) junto <- junto[, -nx] names(junto) <- namexy[c(-1, -(nx + 1))] if(k==1 & nx==2) { junto[,numerico[1]]<-as.character(junto[,numerico[1]]) junto[,numerico[1]]<-as.numeric(junto[,numerico[1]]) junto<-junto[order(junto[,1]),]} if (k>0 & nx > 2) { for (i in 1:k){ junto[,numerico[i]]<-as.character(junto[,numerico[i]]) junto[,numerico[i]]<-as.numeric(junto[,numerico[i]])} junto<-junto[do.call("order", c(junto[,1:(nx-1)])),]} rownames(junto)<-1:(nrow(junto)) return(junto)} regression=function(trat, resp, ylab="Response", xlab="Independent", yname.poly="y", xname.poly="x", grau=NA, theme=theme_classic(), point="mean_sd", color="gray80", posi="top", textsize=12, se=FALSE, ylim=NA, family="sans", pointsize=4.5, linesize=0.8, width.bar=NA, n=NA, SSq=NA, DFres=NA){ requireNamespace("ggplot2") if(is.na(width.bar)==TRUE){width.bar=0.1*mean(trat)} if(is.na(grau)==TRUE){grau=1} dados=data.frame(trat,resp) medias=c() dose=tapply(trat, trat, mean, na.rm=TRUE) mod=c() mod1=c() mod2=c() modm=c() mod1m=c() mod2m=c() text1=c() text2=c() text3=c() mods=c() mod1s=c() mod2s=c() fparcial1=c() fparcial2=c() fparcial3=c() media=tapply(resp, trat, mean, na.rm=TRUE) desvio=tapply(resp, trat, sd, na.rm=TRUE) erro=tapply(resp, trat, sd, na.rm=TRUE)/sqrt(table(trat)) dose=tapply(trat, trat, mean, na.rm=TRUE) moda=lm(resp~trat) mod1a=lm(resp~trat+I(trat^2)) mod2a=lm(resp~trat+I(trat^2)+I(trat^3)) mods=summary(moda)$coefficients mod1s=summary(mod1a)$coefficients mod2s=summary(mod2a)$coefficients modm=lm(media~dose) mod1m=lm(media~dose+I(dose^2)) mod2m=lm(media~dose+I(dose^2)+I(dose^3)) modf1=lm(resp~trat) modf2=lm(resp~trat+I(trat^2)) modf3=lm(resp~trat+I(trat^2)+I(trat^3)) modf1ql=anova(modf1) modf2ql=anova(modf2) modf3ql=anova(modf3) modf1q=aov(resp~as.factor(trat)) res=anova(modf1q) fadj1=anova(modf1,modf1q)[2,c(3,4,5,6)] fadj2=anova(modf2,modf1q)[2,c(3,4,5,6)] fadj3=anova(modf3,modf1q)[2,c(3,4,5,6)] if(is.na(DFres)==TRUE){DFres=res[2,1]} if(is.na(SSq)==TRUE){SSq=res[2,2]} df1=c(modf3ql[1,1],fadj1[1,1],DFres) df2=c(modf3ql[1:2,1],fadj2[1,1],DFres) df3=c(modf3ql[1:3,1],fadj3[1,1],DFres) sq1=c(modf3ql[1,2],fadj1[1,2],SSq) sq2=c(modf3ql[1:2,2],fadj2[1,2],SSq) sq3=c(modf3ql[1:3,2],fadj3[1,2],SSq) qm1=sq1/df1 qm2=sq2/df2 qm3=sq3/df3 if(grau=="1"){fa1=data.frame(cbind(df1,sq1,qm1)) fa1$f1=c(fa1$qm1[1:2]/fa1$qm1[3],NA) fa1$p=c(pf(fa1$f1[1:2],fa1$df1[1:2],fa1$df1[3],lower.tail = F),NA) colnames(fa1)=c("Df","SSq","MSQ","F","p-value");rownames(fa1)=c("Linear","Deviation","Residual")} if(grau=="2"){fa2=data.frame(cbind(df2,sq2,qm2)) fa2$f2=c(fa2$qm2[1:3]/fa2$qm2[4],NA) fa2$p=c(pf(fa2$f2[1:3],fa2$df2[1:3],fa2$df2[4],lower.tail = F),NA) colnames(fa2)=c("Df","SSq","MSQ","F","p-value");rownames(fa2)=c("Linear","Quadratic","Deviation","Residual")} if(grau=="3"){ fa3=data.frame(cbind(df3,sq3,qm3)) fa3$f3=c(fa3$qm3[1:4]/fa3$qm3[5],NA) fa3$p=c(pf(fa3$f3[1:4],fa3$df3[1:4],fa3$df3[5],lower.tail = F),NA) colnames(fa3)=c("Df","SSq","MSQ","F","p-value");rownames(fa3)=c("Linear","Quadratic","Cubic","Deviation","Residual")} if(grau=="1"){r2=round(summary(modm)$r.squared, 2)} if(grau=="2"){r2=round(summary(mod1m)$r.squared, 2)} if(grau=="3"){r2=round(summary(mod2m)$r.squared, 2)} if(grau=="1"){ if(is.na(n)==FALSE){coef1=round(coef(moda)[1],n)}else{coef1=coef(moda)[1]} if(is.na(n)==FALSE){coef2=round(coef(moda)[2],n)}else{coef2=coef(moda)[2]} s1=s <- sprintf("%s == %e %s %e*%s ~~~~~ italic(R^2) == %0.2f", yname.poly, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.poly, r2)} if(grau=="2"){ if(is.na(n)==FALSE){coef1=round(coef(mod1a)[1],n)}else{coef1=coef(mod1a)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod1a)[2],n)}else{coef2=coef(mod1a)[2]} if(is.na(n)==FALSE){coef3=round(coef(mod1a)[3],n)}else{coef3=coef(mod1a)[3]} s2=s <- sprintf("%s == %e %s %e * %s %s %e * %s^2 ~~~~~ italic(R^2) == %0.2f", yname.poly, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.poly, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.poly, r2)} if(grau=="3"){ if(is.na(n)==FALSE){coef1=round(coef(mod2a)[1],n)}else{coef1=coef(mod2a)[1]} if(is.na(n)==FALSE){coef2=round(coef(mod2a)[2],n)}else{coef2=coef(mod2a)[2]} if(is.na(n)==FALSE){coef3=round(coef(mod2a)[3],n)}else{coef3=coef(mod2a)[3]} if(is.na(n)==FALSE){coef4=round(coef(mod2a)[4],n)}else{coef4=coef(mod2a)[4]} s3=s <- sprintf("%s == %e %s %e * %s %s %e * %s^2 %s %0.e * %s^3 ~~~~~ italic(R^2) == %0.2f", yname.poly, coef1, ifelse(coef2 >= 0, "+", "-"), abs(coef2), xname.poly, ifelse(coef3 >= 0, "+", "-"), abs(coef3), xname.poly, ifelse(coef4 >= 0, "+", "-"), abs(coef4), xname.poly, r2)} data1=data.frame(trat,resp) data1=data.frame(trat=dose,#as.numeric(as.character(names(media))), resp=media, desvio, erro) grafico=ggplot(data1,aes(x=trat,y=resp)) if(point=="all"){grafico=grafico+ geom_point(data=dados, aes(y=resp,x=trat),shape=21, fill=color,color="black")} if(point=="mean_sd"){grafico=grafico+ geom_errorbar(aes(ymin=resp-desvio,ymax=resp+desvio),width=width.bar,size=linesize)} if(point=="mean_se"){grafico=grafico+ geom_errorbar(aes(ymin=resp-erro,ymax=resp+erro),width=width.bar,size=linesize)} if(point=="mean"){grafico=grafico} grafico=grafico+geom_point(aes(fill=as.factor(rep(1,length(resp)))),na.rm=TRUE, size=pointsize,shape=21, color="black")+ theme+ylab(ylab)+xlab(xlab) if(is.na(ylim[1])==TRUE){grafico=grafico}else{grafico=grafico+ylim(ylim)} if(grau=="0"){grafico=grafico+geom_line(y=mean(resp),size=linesize,lty=2)} if(grau=="1"){grafico=grafico+geom_smooth(method = "lm",se=se, na.rm=TRUE, formula = y~x,size=linesize,color="black")} if(grau=="2"){grafico=grafico+geom_smooth(method = "lm",se=se, na.rm=TRUE, formula = y~x+I(x^2),size=linesize,color="black")} if(grau=="3"){grafico=grafico+geom_smooth(method = "lm",se=se, na.rm=TRUE, formula = y~x+I(x^2)+I(x^3),size=linesize,color="black")} if(grau=="0"){grafico=grafico+ scale_fill_manual(values=color,label=paste("y =",round(mean(resp),3)),name="")} if(grau=="1"){grafico=grafico+ scale_fill_manual(values=color,label=c(parse(text=s1)),name="")} if(grau=="2"){grafico=grafico+ scale_fill_manual(values=color,label=c(parse(text=s2)),name="")} if(grau=="3"){grafico=grafico+ scale_fill_manual(values=color,label=c(parse(text=s3)),name="")} if(color=="gray"){if(grau=="1"){grafico=grafico+ scale_fill_manual(values="black",label=c(parse(text=s1)),name="")} if(grau=="2"){grafico=grafico+ scale_fill_manual(values="black",label=c(parse(text=s2)),name="")} if(grau=="3"){grafico=grafico+ scale_fill_manual(values="black",label=c(parse(text=s3)),name="")} } grafico=grafico+ theme(text = element_text(size=textsize,color="black",family=family), axis.text = element_text(size=textsize,color="black",family=family), axis.title = element_text(size=textsize,color="black",family=family), legend.position = posi, legend.text=element_text(size=textsize), legend.direction = "vertical", legend.text.align = 0, legend.justification = 0) print(grafico) if(grau==1){ cat("\n----------------------------------------------------\n") cat("Regression Models") cat("\n----------------------------------------------------\n") print(mods) cat("\n----------------------------------------------------\n") cat("Deviations from regression") cat("\n----------------------------------------------------\n") print(as.matrix(fa1),na.print=" ") } if(grau==2){ cat("\n----------------------------------------------------\n") cat("Regression Models") cat("\n----------------------------------------------------\n") print(mod1s) cat("\n----------------------------------------------------\n") cat("Deviations from regression") cat("\n----------------------------------------------------\n") print(as.matrix(fa2),na.print=" ") } if(grau==3){ cat("\n----------------------------------------------------\n") cat("Regression Models") cat("\n----------------------------------------------------\n") print(mod2s) cat("\n----------------------------------------------------\n") cat("Deviations from regression") cat("\n----------------------------------------------------\n") print(as.matrix(fa3),na.print=" ") } graficos=list(grafico) } levenehomog <- function (y, ...) { UseMethod("levenehomog")} levenehomog.default <- function (y, group, center=median, ...) { if (!is.numeric(y)) stop(deparse(substitute(y)), " is not a numeric variable") if (!is.factor(group)){warning(deparse(substitute(group)), " coerced to factor.") group <- as.factor(group)} valid <- complete.cases(y, group) meds <- tapply(y[valid], group[valid], center, ...) resp <- abs(y - meds[group]) table <- anova(lm(resp ~ group))[, c(1, 4, 5)] rownames(table)[2] <- " " dots <- deparse(substitute(...)) attr(table, "heading") <- paste("Levene's Test (center = ", deparse(substitute(center)), if(!(dots == "NULL")) paste(":", dots), ")", sep="") table} levenehomog.formula <- function(y, data, ...) { form <- y mf <- if (missing(data)) model.frame(form) else model.frame(form, data) if (any(sapply(2:dim(mf)[2], function(j) is.numeric(mf[[j]])))) stop("Levene's test is not appropriate with quantitative explanatory variables.") y <- mf[,1] if(dim(mf)[2]==2) group <- mf[,2] else { if (length(grep("\\+ | \\| | \\^ | \\:",form))>0) stop("Model must be completely crossed formula only.") group <- interaction(mf[,2:dim(mf)[2]])} levenehomog.default(y=y, group=group, ...)} levenehomog.lm <- function(y, ...) { m <- model.frame(y) m$..y <- model.response(m) f <- formula(y) f[2] <- expression(..y) levenehomog.formula(f, data=m, ...)} ordenacao=function (treatment, means, alpha, pvalue, console){ n <- length(means) z <- data.frame(treatment, means) letras<-c(letters[1:26],LETTERS[1:26],1:9, c(".","+","-","*","/","#","$","%","&","^","[","]",":", "@",";","_","?","!","=","#",rep(" ",2000))) w <- z[order(z[, 2], decreasing = TRUE), ] M<-rep("",n) k<-1 k1<-0 j<-1 i<-1 cambio<-n cambio1<-0 chequeo=0 M[1]<-letras[k] q <- as.numeric(rownames(w)) #Check while(j<n) { chequeo<-chequeo+1 if (chequeo > n) break for(i in j:n) { s<-pvalue[q[i],q[j]]>alpha if(s) { if(lastC(M[i]) != letras[k])M[i]<-paste(M[i],letras[k],sep="") } else { k<-k+1 cambio<-i cambio1<-0 ja<-j for(jj in cambio:n) M[jj]<-paste(M[jj],"",sep="") # El espacio M[cambio]<-paste(M[cambio],letras[k],sep="") for( v in ja:cambio) { if(pvalue[q[v],q[cambio]]<=alpha) {j<-j+1 cambio1<-1 } else break } break } } if (cambio1 ==0 )j<-j+1 } w<-data.frame(w,stat=M) trt <- as.character(w$treatment) means <- as.numeric(w$means) output <- data.frame(means, groups=M) rownames(output)<-trt if(k>81) cat("\n",k,"groups are estimated.The number of groups exceeded the maximum of 81 labels. change to group=FALSE.\n") invisible(output) } lastC <-function(x) { y<-sub(" +$", "",x) p1<-nchar(y) cc<-substr(y,p1,p1) return(cc)} duncan <- function(y,trt,DFerror,MSerror,alpha = 0.05, group = TRUE,main = NULL,console = FALSE){name.y <- paste(deparse(substitute(y))) name.t <- paste(deparse(substitute(trt))) if(is.null(main))main<-paste(name.y,"~", name.t) clase<-c("aov","lm") if("aov"%in%class(y) | "lm"%in%class(y)){ if(is.null(main))main<-y$call A<-y$model DFerror<-df.residual(y) MSerror<-deviance(y)/DFerror y<-A[,1] ipch<-pmatch(trt,names(A)) nipch<- length(ipch) for(i in 1:nipch){ if (is.na(ipch[i])) return(if(console)cat("Name: ", trt, "\n", names(A)[-1], "\n"))} name.t<- names(A)[ipch][1] trt <- A[, ipch] if (nipch > 1){ trt <- A[, ipch[1]] for(i in 2:nipch){ name.t <- paste(name.t,names(A)[ipch][i],sep=":") trt <- paste(trt,A[,ipch[i]],sep=":") }} name.y <- names(A)[1] } junto <- subset(data.frame(y, trt), is.na(y) == FALSE) Mean<-mean(junto[,1]) CV<-sqrt(MSerror)*100/Mean medians<-mean.stat(junto[,1],junto[,2],stat="median") for(i in c(1,5,2:4)) { x <- mean.stat(junto[,1],junto[,2],function(x)quantile(x)[i]) medians<-cbind(medians,x[,2]) } medians<-medians[,3:7] names(medians)<-c("Min","Max","Q25","Q50","Q75") means <- mean.stat(junto[,1],junto[,2],stat="mean") # change sds <- mean.stat(junto[,1],junto[,2],stat="sd") #change nn <- mean.stat(junto[,1],junto[,2],stat="length") # change means<-data.frame(means,std=sds[,2],r=nn[,2],medians) names(means)[1:2]<-c(name.t,name.y) ntr<-nrow(means) Tprob<-NULL k<-0 for(i in 2:ntr){ k<-k+1 x <- suppressWarnings(warning(qtukey((1-alpha)^(i-1), i, DFerror))) if(x=="NaN")break else Tprob[k]<-x } if(k<(ntr-1)){ for(i in k:(ntr-1)){ f <- Vectorize(function(x)ptukey(x,i+1,DFerror)-(1-alpha)^i) Tprob[i]<-uniroot(f, c(0,100))$root } } Tprob<-as.numeric(Tprob) nr <- unique(nn[,2]) if(console){ cat("\nStudy:", main) cat("\n\nDuncan's new multiple range test\nfor",name.y,"\n") cat("\nMean Square Error: ",MSerror,"\n\n") cat(paste(name.t,",",sep="")," means\n\n") print(data.frame(row.names = means[,1], means[,2:6])) } if(length(nr) == 1 ) sdtdif <- sqrt(MSerror/nr) else { nr1 <- 1/mean(1/nn[,2]) sdtdif <- sqrt(MSerror/nr1) } DUNCAN <- Tprob * sdtdif names(DUNCAN)<-2:ntr duncan<-data.frame(Table=Tprob,CriticalRange=DUNCAN) if ( group & length(nr) == 1 & console){ cat("\nAlpha:",alpha,"; DF Error:",DFerror,"\n") cat("\nCritical Range\n") print(DUNCAN)} if ( group & length(nr) != 1 & console) cat("\nGroups according to probability of means differences and alpha level(",alpha,")\n") if ( length(nr) != 1) duncan<-NULL Omeans<-order(means[,2],decreasing = TRUE) #correccion 2019, 1 abril. Ordindex<-order(Omeans) comb <-utils::combn(ntr,2) nn<-ncol(comb) dif<-rep(0,nn) DIF<-dif LCL<-dif UCL<-dif pvalue<-dif odif<-dif sig<-NULL for (k in 1:nn) { i<-comb[1,k] j<-comb[2,k] dif[k]<-means[i,2]-means[j,2] DIF[k]<-abs(dif[k]) nx<-abs(i-j)+1 odif[k] <- abs(Ordindex[i]- Ordindex[j])+1 pvalue[k]<- round(1-ptukey(DIF[k]/sdtdif,odif[k],DFerror)^(1/(odif[k]-1)),4) LCL[k] <- dif[k] - DUNCAN[odif[k]-1] UCL[k] <- dif[k] + DUNCAN[odif[k]-1] sig[k]<-" " if (pvalue[k] <= 0.001) sig[k]<-"***" else if (pvalue[k] <= 0.01) sig[k]<-"**" else if (pvalue[k] <= 0.05) sig[k]<-"*" else if (pvalue[k] <= 0.1) sig[k]<-"." } if(!group){ tr.i <- means[comb[1, ],1] tr.j <- means[comb[2, ],1] comparison<-data.frame("difference" = dif, pvalue=pvalue,"signif."=sig,LCL,UCL) rownames(comparison)<-paste(tr.i,tr.j,sep=" - ") if(console){cat("\nComparison between treatments means\n\n") print(comparison)} groups=NULL } if (group) { comparison=NULL Q<-matrix(1,ncol=ntr,nrow=ntr) p<-pvalue k<-0 for(i in 1:(ntr-1)){ for(j in (i+1):ntr){ k<-k+1 Q[i,j]<-p[k] Q[j,i]<-p[k] } } groups <- ordenacao(means[, 1], means[, 2],alpha, Q,console) names(groups)[1]<-name.y if(console) { cat("\nMeans with the same letter are not significantly different.\n\n") print(groups) } } parameters<-data.frame(test="Duncan",name.t=name.t,ntr = ntr,alpha=alpha) statistics<-data.frame(MSerror=MSerror,Df=DFerror,Mean=Mean,CV=CV) rownames(parameters)<-" " rownames(statistics)<-" " rownames(means)<-means[,1] means<-means[,-1] output<-list(statistics=statistics,parameters=parameters, duncan=duncan, means=means,comparison=comparison,groups=groups) class(output)<-"group" invisible(output) } TUKEY <- function(y, trt, DFerror, MSerror, alpha=0.05, group=TRUE, main = NULL,unbalanced=FALSE,console=FALSE){ name.y <- paste(deparse(substitute(y))) name.t <- paste(deparse(substitute(trt))) if(is.null(main))main<-paste(name.y,"~", name.t) clase<-c("aov","lm") if("aov"%in%class(y) | "lm"%in%class(y)){ if(is.null(main))main<-y$call A<-y$model DFerror<-df.residual(y) MSerror<-deviance(y)/DFerror y<-A[,1] ipch<-pmatch(trt,names(A)) nipch<- length(ipch) for(i in 1:nipch){ if (is.na(ipch[i])) return(if(console)cat("Name: ", trt, "\n", names(A)[-1], "\n")) } name.t<- names(A)[ipch][1] trt <- A[, ipch] if (nipch > 1){ trt <- A[, ipch[1]] for(i in 2:nipch){ name.t <- paste(name.t,names(A)[ipch][i],sep=":") trt <- paste(trt,A[,ipch[i]],sep=":") }} name.y <- names(A)[1] } junto <- subset(data.frame(y, trt), is.na(y) == FALSE) Mean<-mean(junto[,1]) CV<-sqrt(MSerror)*100/Mean medians<-mean.stat(junto[,1],junto[,2],stat="median") for(i in c(1,5,2:4)) { x <- mean.stat(junto[,1],junto[,2],function(x)quantile(x)[i]) medians<-cbind(medians,x[,2]) } medians<-medians[,3:7] names(medians)<-c("Min","Max","Q25","Q50","Q75") means <- mean.stat(junto[,1],junto[,2],stat="mean") sds <- mean.stat(junto[,1],junto[,2],stat="sd") nn <- mean.stat(junto[,1],junto[,2],stat="length") means<-data.frame(means,std=sds[,2],r=nn[,2],medians) names(means)[1:2]<-c(name.t,name.y) ntr<-nrow(means) Tprob <- qtukey(1-alpha,ntr, DFerror) nr<-unique(nn[, 2]) nr1<-1/mean(1/nn[,2]) if(console){ cat("\nStudy:", main) cat("\n\nHSD Test for",name.y,"\n") cat("\nMean Square Error: ",MSerror,"\n\n") cat(paste(name.t,",",sep="")," means\n\n") print(data.frame(row.names = means[,1], means[,2:6])) cat("\nAlpha:",alpha,"; DF Error:",DFerror,"\n") cat("Critical Value of Studentized Range:", Tprob,"\n") } HSD <- Tprob * sqrt(MSerror/nr) statistics<-data.frame(MSerror=MSerror,Df=DFerror,Mean=Mean,CV=CV,MSD=HSD) if ( group & length(nr) == 1 & console) cat("\nMinimun Significant Difference:",HSD,"\n") if ( group & length(nr) != 1 & console) cat("\nGroups according to probability of means differences and alpha level(",alpha,")\n") if ( length(nr) != 1) statistics<-data.frame(MSerror=MSerror,Df=DFerror,Mean=Mean,CV=CV) comb <-utils::combn(ntr,2) nn<-ncol(comb) dif<-rep(0,nn) sig<-NULL LCL<-dif UCL<-dif pvalue<-rep(0,nn) for (k in 1:nn) { i<-comb[1,k] j<-comb[2,k] dif[k]<-means[i,2]-means[j,2] sdtdif<-sqrt(MSerror * 0.5*(1/means[i,4] + 1/means[j,4])) if(unbalanced)sdtdif<-sqrt(MSerror /nr1) pvalue[k]<- round(1-ptukey(abs(dif[k])/sdtdif,ntr,DFerror),4) LCL[k] <- dif[k] - Tprob*sdtdif UCL[k] <- dif[k] + Tprob*sdtdif sig[k]<-" " if (pvalue[k] <= 0.001) sig[k]<-"***" else if (pvalue[k] <= 0.01) sig[k]<-"**" else if (pvalue[k] <= 0.05) sig[k]<-"*" else if (pvalue[k] <= 0.1) sig[k]<-"." } if(!group){ tr.i <- means[comb[1, ],1] tr.j <- means[comb[2, ],1] comparison<-data.frame("difference" = dif, pvalue=pvalue,"signif."=sig,LCL,UCL) rownames(comparison)<-paste(tr.i,tr.j,sep=" - ") if(console){cat("\nComparison between treatments means\n\n") print(comparison)} groups=NULL } if (group) { comparison=NULL Q<-matrix(1,ncol=ntr,nrow=ntr) p<-pvalue k<-0 for(i in 1:(ntr-1)){ for(j in (i+1):ntr){ k<-k+1 Q[i,j]<-p[k] Q[j,i]<-p[k] } } groups <- ordenacao(means[, 1], means[, 2],alpha, Q,console) names(groups)[1]<-name.y if(console) { cat("\nTreatments with the same letter are not significantly different.\n\n") print(groups) } } parameters<-data.frame(test="Tukey",name.t=name.t,ntr = ntr, StudentizedRange=Tprob,alpha=alpha) rownames(parameters)<-" " rownames(statistics)<-" " rownames(means)<-means[,1] means<-means[,-1] output<-list(statistics=statistics,parameters=parameters, means=means,comparison=comparison,groups=groups) class(output)<-"group" invisible(output) } sk<-function(y, trt, DFerror, SSerror, alpha = 0.05, group = TRUE, main = NULL){ sk <- function(medias,s2,dfr,prob){ bo <- 0 si2 <- s2 defr <- dfr parou <- 1 np <- length(medias) - 1 for (i in 1:np){ g1 <- medias[1:i] g2 <- medias[(i+1):length(medias)] B0 <- sum(g1)^2/length(g1) + sum(g2)^2/length(g2) - (sum(g1) + sum(g2))^2/length(c(g1,g2)) if (B0 > bo) {bo <- B0 parou <- i} } g1 <- medias[1:parou] g2 <- medias[(parou+1):length(medias)] teste <- c(g1,g2) sigm2 <- (sum(teste^2) - sum(teste)^2/length(teste) + defr*si2)/(length(teste) + defr) lamb <- pi*bo/(2*sigm2*(pi-2)) v0 <- length(teste)/(pi-2) p <- pchisq(lamb,v0,lower.tail = FALSE) if (p < prob) { for (i in 1:length(g1)){ cat(names(g1[i]),"\n",file="sk_groups",append=TRUE)} cat("*","\n",file="sk_groups",append=TRUE)} if (length(g1)>1){sk(g1,s2,dfr,prob)} if (length(g2)>1){sk(g2,s2,dfr,prob)} } trt=factor(trt,unique(trt)) trt1=trt levels(trt)=paste("T",1:length(levels(trt)),sep = "") medias <- sort(tapply(y,trt,mean),decreasing=TRUE) dfr <- DFerror rep <- tapply(y,trt,length) s0 <- MSerror <-SSerror/DFerror s2 <- s0/rep[1] prob <- alpha sk(medias,s2,dfr,prob) f <- names(medias) names(medias) <- 1:length(medias) resultado <- data.frame("r"=0,"f"=f,"m"=medias) if (file.exists("sk_groups") == FALSE) {stop} else{ xx <- read.table("sk_groups") file.remove("sk_groups") x <- xx[[1]] x <- as.vector(x) z <- 1 for (j in 1:length(x)){ if (x[j] == "*") {z <- z+1} for (i in 1:length(resultado$f)){ if (resultado$f[i]==x[j]){ resultado$r[i] <- z;} } } } letras<-letters if(length(resultado$r)>26) { l<-floor(length(resultado$r)/26) for(i in 1:l) letras<-c(letras,paste(letters,i,sep='')) } res <- 1 for (i in 1:(length(resultado$r)-1)) { if (resultado$r[i] != resultado$r[i+1]){ resultado$r[i] <- letras[res] res <- res+1 if (i == (length(resultado$r)-1)){ resultado$r[i+1] <- letras[res]} } else{ resultado$r[i] <- letras[res] if (i == (length(resultado$r)-1)){ resultado$r[i+1] <- letras[res] } } } names(resultado) <- c("groups","Tratamentos","Means") resultado1=resultado[,c(3,1)] rownames(resultado1)=resultado$Tratamentos final=list(resultado1)[[1]] final=final[as.character(unique(trt)),] rownames(final)=as.character(unique(trt1)) final } scottknott=function(means, df1, QME, nrep, alpha=0.05){ sk1=function(means, df1, QME, nrep, alpha=alpha) { means=sort(means,decreasing=TRUE) n=1:(length(means)-1) n=as.list(n) f=function(n){list(means[c(1:n)],means[-c(1:n)])} g=lapply(n, f) b1=function(x){(sum(g[[x]][[1]])^2)/length(g[[x]][[1]]) + (sum(g[[x]][[2]])^2)/length(g[[x]][[2]])- (sum(c(g[[x]][[1]],g[[x]][[2]]))^2)/length(c(g[[x]][[1]],g[[x]][[2]]))} p=1:length(g) values=sapply(p,b1) minimo=min(values); maximo=max(values) alfa=(1/(length(means)+df1))*(sum((means-mean(means))^2)+(df1*QME/nrep)) lambda=(pi/(2*(pi-2)))*(maximo/alfa) vq=qchisq((alpha),lower.tail=FALSE, df=length(means)/(pi-2)) ll=1:length(values); da=data.frame(ll,values); da=da[order(-values),] ran=da$ll[1] r=g[[ran]]; r=as.list(r) i=ifelse(vq>lambda|length(means)==1, 1,2) means=list(means) res=list(means, r) return(res[[i]]) } u=sk1(means, df1, QME, nrep, alpha=alpha) u=lapply(u, sk1, df1=df1, QME=QME, nrep=nrep, alpha=alpha) sk2=function(u){ v1=function(...){c(u[[1]])} v2=function(...){c(u[[1]],u[[2]])} v3=function(...){c(u[[1]],u[[2]],u[[3]])} v4=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]])} v5=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]])} v6=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]])} v7=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]],u[[7]])} v8=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]],u[[7]],u[[8]])} v9=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]],u[[7]],u[[8]],u[[9]])} v10=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]],u[[7]],u[[8]],u[[9]],u[[10]])} lv=list(v1,v2,v3,v4,v5,v6,v7,v8,v9,v10) l=length(u) ti=lv[[l]] u=ti() u=lapply(u, sk1, df1=df1, QME=QME, nrep=nrep, alpha=alpha) return(u) } u=sk2(u);u=sk2(u);u=sk2(u);u=sk2(u);u=sk2(u) u=sk2(u);u=sk2(u);u=sk2(u);u=sk2(u);u=sk2(u) v1=function(...){c(u[[1]])} v2=function(...){c(u[[1]],u[[2]])} v3=function(...){c(u[[1]],u[[2]],u[[3]])} v4=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]])} v5=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]])} v6=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]])} v7=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]],u[[7]])} v8=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]],u[[7]],u[[8]])} v9=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]],u[[7]],u[[8]],u[[9]])} v10=function(...){c(u[[1]],u[[2]],u[[3]],u[[4]],u[[5]],u[[6]],u[[7]],u[[8]],u[[9]],u[[10]])} lv=list(v1,v2,v3,v4,v5,v6,v7,v8,v9,v10) l=length(u) ti=lv[[l]] u=ti() rp=u l2=lapply(rp, length) l2=unlist(l2) rp2=rep(letters[1:length(rp)], l2) return(rp2)} requireNamespace("crayon") requireNamespace("ggplot2") requireNamespace("nortest") if(is.na(sup==TRUE)){sup=0.2*mean(response, na.rm=TRUE)} if(angle.label==0){hjust=0.5}else{hjust=0} if(test=="parametric"){ if(transf==1){resp=response+constant}else{resp=((response+constant)^transf-1)/transf} if(transf==0){resp=log(response+constant)} if(transf==0.5){resp=sqrt(response+constant)} if(transf==-0.5){resp=1/sqrt(response+constant)} if(transf==-1){resp=1/(response+constant)} trat1=trat trat=as.factor(trat) bloco=as.factor(block) a = anova(aov(resp ~ trat + bloco)) b = aov(resp ~ trat + bloco) anava=a colnames(anava)=c("GL","SQ","QM","Fcal","p-value") respad=b$residuals/sqrt(a$`Mean Sq`[3]) out=respad[respad>3 | respad<(-3)] out=names(out) out=if(length(out)==0)("No discrepant point")else{out} if(norm=="sw"){norm1 = shapiro.test(b$res)} if(norm=="li"){norm1=lillie.test(b$residuals)} if(norm=="ad"){norm1=ad.test(b$residuals)} if(norm=="cvm"){norm1=cvm.test(b$residuals)} if(norm=="pearson"){norm1=pearson.test(b$residuals)} if(norm=="sf"){norm1=sf.test(b$residuals)} if(homog=="bt"){ homog1 = bartlett.test(b$res ~ trat) statistic=homog1$statistic phomog=homog1$p.value method=paste("Bartlett test","(",names(statistic),")",sep="") } if(homog=="levene"){ homog1 = levenehomog(b$res~trat)[1,] statistic=homog1$`F value`[1] phomog=homog1$`Pr(>F)`[1] method="Levene's Test (center = median)(F)" names(homog1)=c("Df", "F value","p.value")} indep = dwtest(b) resids=b$residuals/sqrt(a$`Mean Sq`[3]) Ids=ifelse(resids>3 | resids<(-3), "darkblue","black") residplot=ggplot(data=data.frame(resids,Ids),aes(y=resids,x=1:length(resids)))+ geom_point(shape=21,color="gray",fill="gray",size=3)+ labs(x="",y="Standardized residuals")+ geom_text(x=1:length(resids),label=1:length(resids),color=Ids,size=4)+ scale_x_continuous(breaks=1:length(resids))+ theme_classic()+ theme(axis.text.y = element_text(size=12), axis.text.x = element_blank())+ geom_hline(yintercept = c(0,-3,3),lty=c(1,2,2),color="red",size=1) print(residplot) cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(green(bold("Normality of errors"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) normal=data.frame(Method=paste(norm1$method,"(",names(norm1$statistic),")",sep=""), Statistic=norm1$statistic, "p-value"=norm1$p.value) rownames(normal)="" print(normal) cat("\n") message(if(norm1$p.value>0.05){ black("As the calculated p-value is greater than the 5% significance level, hypothesis H0 is not rejected. Therefore, errors can be considered normal")} else {"As the calculated p-value is less than the 5% significance level, H0 is rejected. Therefore, errors do not follow a normal distribution"}) cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(green(bold("Homogeneity of Variances"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) homoge=data.frame(Method=method, Statistic=statistic, "p-value"=phomog) rownames(homoge)="" print(homoge) cat("\n") message(if(homog1$p.value>0.05){ black("As the calculated p-value is greater than the 5% significance level, hypothesis H0 is not rejected. Therefore, the variances can be considered homogeneous")} else {"As the calculated p-value is less than the 5% significance level, H0 is rejected. Therefore, the variances are not homogeneous"}) cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(green(bold("Independence from errors"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) indepe=data.frame(Method=paste(indep$method,"(", names(indep$statistic),")",sep=""), Statistic=indep$statistic, "p-value"=indep$p.value) rownames(indepe)="" print(indepe) cat("\n") message(if(indep$p.value>0.05){ black("As the calculated p-value is greater than the 5% significance level, hypothesis H0 is not rejected. Therefore, errors can be considered independent")} else {"As the calculated p-value is less than the 5% significance level, H0 is rejected. Therefore, errors are not independent"}) cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(green(bold("Additional Information"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(paste("\nCV (%) = ",round(sqrt(a$`Mean Sq`[3])/mean(resp,na.rm=TRUE)*100,2))) cat(paste("\nR-squared = ",round(a$`Mean Sq`[1]/(a$`Mean Sq`[3]+a$`Mean Sq`[2]+a$`Mean Sq`[1]),2))) cat(paste("\nMean = ",round(mean(response,na.rm=TRUE),4))) cat(paste("\nMedian = ",round(median(response,na.rm=TRUE),4))) cat("\nPossible outliers = ", out) cat("\n") cat(green(bold("\n-----------------------------------------------------------------\n"))) cat(green(bold("Analysis of Variance"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) anava1=as.matrix(data.frame(anava)) colnames(anava1)=c("Df","Sum Sq","Mean.Sq","F value","Pr(F)" ) print(anava1,na.print = "") cat("\n") message(if (a$`Pr(>F)`[1]<alpha.f){ black("As the calculated p-value, it is less than the 5% significance level. The hypothesis H0 of equality of means is rejected. Therefore, at least two treatments differ")} else {"As the calculated p-value is greater than the 5% significance level, H0 is not rejected"}) cat(green(bold("\n-----------------------------------------------------------------\n"))) if(quali==TRUE){cat(green(bold("Multiple Comparison Test")))}else{cat(green(bold("Regression")))} cat(green(bold("\n-----------------------------------------------------------------\n"))) if(quali==TRUE){ if(mcomp=="tukey"){ letra <- TUKEY(b, "trat", alpha=alpha.t) letra1 <- letra$groups; colnames(letra1)=c("resp","groups")} if(mcomp=="sk"){ nrep=table(trat)[1] medias=sort(tapply(resp,trat,mean),decreasing = TRUE) letra=scottknott(means = medias, df1 = a$Df[3], nrep = nrep, QME = a$`Mean Sq`[3], alpha = alpha.t) letra1=data.frame(resp=medias,groups=letra)} if(mcomp=="duncan"){ letra <- duncan(b, "trat", alpha=alpha.t) letra1 <- letra$groups; colnames(letra1)=c("resp","groups")} media = tapply(response, trat, mean, na.rm=TRUE) if(transf=="1"){letra1}else{letra1$respO=media[rownames(letra1)]} print(if(a$`Pr(>F)`[1]<alpha.f){letra1}else{"H0 is not rejected"}) cat("\n") cat(if(transf=="1"){}else{blue("resp = transformed means; respO = averages without transforming")}) if(transf==1 && norm1$p.value<0.05 | transf==1 && indep$p.value<0.05 | transf==1 &&homog1$p.value<0.05){ message("\nYour analysis is not valid, suggests using a non-parametric \ntest and try to transform the data")} else{} if(transf != 1 && norm1$p.value<0.05 | transf!=1 && indep$p.value<0.05 | transf!=1 && homog1$p.value<0.05){cat(red("\n \nWarning!!! Your analysis is not valid, suggests using a non-parametric \ntest"))}else{} if(point=="mean_sd"){ dadosm=data.frame(letra1, media=tapply(response, trat, mean, na.rm=TRUE)[rownames(letra1)], desvio=tapply(response, trat, sd, na.rm=TRUE)[rownames(letra1)])} if(point=="mean_se"){ dadosm=data.frame(letra1, media=tapply(response, trat, mean, na.rm=TRUE)[rownames(letra1)], desvio=tapply(response, trat, sd, na.rm=TRUE)/sqrt(tapply(response, trat, length))[rownames(letra1)])} dadosm$trats=factor(rownames(dadosm),levels = unique(trat)) dadosm$limite=dadosm$media+dadosm$desvio dadosm=dadosm[unique(as.character(trat)),] if(addmean==TRUE){dadosm$letra=paste(format(dadosm$media,digits = dec),dadosm$groups)} if(addmean==FALSE){dadosm$letra=dadosm$groups} trats=dadosm$trats limite=dadosm$limite media=dadosm$media desvio=dadosm$desvio letra=dadosm$letra if(geom=="bar"){grafico=ggplot(dadosm,aes(x=trats, y=media)) if(fill=="trat"){grafico=grafico+ geom_col(aes(fill=trats),color=1)} else{grafico=grafico+geom_col(aes(fill=trats), fill=fill,color=1)} if(errorbar==TRUE){grafico=grafico+ geom_text(aes(y=media+sup+if(sup<0){-desvio}else{desvio},label=letra), family=family,angle=angle.label, size=labelsize,hjust=hjust)} if(errorbar==FALSE){grafico=grafico+ geom_text(aes(y=media+sup,label=letra), family=family,angle=angle.label,size=labelsize, hjust=hjust)} if(errorbar==TRUE){grafico=grafico+ geom_errorbar(data=dadosm,aes(ymin=media-desvio, ymax=media+desvio,color=1), color="black", width=0.3)}} if(geom=="point"){grafico=ggplot(dadosm,aes(x=trats, y=media)) if(errorbar==TRUE){grafico=grafico+ geom_text(aes(y=media+sup+if(sup<0){-desvio}else{desvio},label=letra), family=family,angle=angle.label, size=labelsize,hjust=hjust)} if(errorbar==FALSE){grafico=grafico+ geom_text(aes(y=media+sup,label=letra),family=family,size=labelsize,angle=angle.label, hjust=hjust)} if(errorbar==TRUE){grafico=grafico+ geom_errorbar(data=dadosm,aes(ymin=media-desvio, ymax=media+desvio,color=1), color="black", width=0.3)} if(fill=="trat"){grafico=grafico+ geom_point(aes(color=trats),size=5)} else{grafico=grafico+ geom_point(aes(color=trats),fill="gray",pch=21,color="black",size=5)}} if(geom=="box"){ datam1=data.frame(trats=factor(trat,levels = unique(as.character(trat))),response) dadosm2=data.frame(letra1, superior=tapply(response, trat, mean, na.rm=TRUE)[rownames(letra1)]) dadosm2$trats=rownames(dadosm2) dadosm2=dadosm2[unique(as.character(trat)),] dadosm2$limite=dadosm$media+dadosm$desvio dadosm2$letra=paste(format(dadosm$media,digits = dec),dadosm$groups) trats=dadosm2$trats limite=dadosm2$limite superior=dadosm2$superior letra=dadosm2$letra stat_box=ggplot(datam1,aes(x=trats,y=response))+geom_boxplot() superior=ggplot_build(stat_box)$data[[1]]$ymax dadosm2$superior=superior+sup grafico=ggplot(datam1,aes(x=trats, y=response)) if(fill=="trat"){grafico=grafico+ geom_boxplot(aes(fill=trats))} else{grafico=grafico+ geom_boxplot(aes(fill=trats),fill=fill)} grafico=grafico+ geom_text(data=dadosm2,aes(y=superior,label=letra), family=family,size=labelsize,angle=angle.label, hjust=hjust)} grafico=grafico+theme+ ylab(ylab)+ xlab(xlab)+ theme(text = element_text(size=textsize,color="black",family=family), axis.text = element_text(size=textsize,color="black",family=family), axis.title = element_text(size=textsize,color="black",family=family), legend.position = "none") if(angle !=0){grafico=grafico+theme(axis.text.x=element_text(hjust = 1.01,angle = angle))} if(CV==TRUE){grafico=grafico+labs(caption=paste("p-value", if(a$`Pr(>F)`[1]<0.0001){paste("<", 0.0001)} else{paste("=", round(a$`Pr(>F)`[1],4))},"; CV = ", round(abs(sqrt(a$`Mean Sq`[3])/mean(resp))*100,2),"%"))} } if(quali==FALSE){ trat=trat1 if(grau==1){graph=regression(trat,response, grau = 1,xlab=xlab,ylab=ylab,textsize=textsize, family=family,posi=posi,point=point,SSq = a$`Sum Sq`[3],DFres = a$Df[3])} if(grau==2){graph=regression(trat,response, grau = 2,xlab=xlab,ylab=ylab,textsize=textsize, family=family,posi=posi,point=point,SSq = a$`Sum Sq`[3],DFres = a$Df[3])} if(grau==3){graph=regression(trat,response, grau = 3,xlab=xlab,ylab=ylab,textsize=textsize, family=family,posi=posi,point=point,SSq = a$`Sum Sq`[3],DFres = a$Df[3])} grafico=graph[[1]] }} if(test=="noparametric"){ friedman=function(judge,trt,evaluation,alpha=0.05,group=TRUE,main=NULL,console=FALSE){ name.x <- paste(deparse(substitute(judge))) name.y <- paste(deparse(substitute(evaluation))) name.t <- paste(deparse(substitute(trt))) name.j <- paste(deparse(substitute(judge))) if(is.null(main))main<-paste(name.y,"~", name.j,"+",name.t) datos <- data.frame(judge, trt, evaluation) matriz <- by(datos[,3], datos[,1:2], function(x) mean(x,na.rm=TRUE)) matriz <-as.data.frame(matriz[,]) name<-as.character(colnames(matriz)) ntr <-length(name) m<-dim(matriz) v<-array(0,m) for (i in 1:m[1]){ v[i,]<-rank(matriz[i,]) } vv<-as.numeric(v) junto <- data.frame(evaluation, trt) medians<-mean.stat(junto[,1],junto[,2],stat="median") for(i in c(1,5,2:4)) { x <- mean.stat(junto[,1],junto[,2],function(x)quantile(x)[i]) medians<-cbind(medians,x[,2])} medians<-medians[,3:7] names(medians)<-c("Min","Max","Q25","Q50","Q75") Means <- mean.stat(junto[,1],junto[,2],stat="mean") sds <- mean.stat(junto[,1],junto[,2],stat="sd") nn <- mean.stat(junto[,1],junto[,2],stat="length") nr<-unique(nn[,2]) s<-array(0,m[2]) for (j in 1:m[2]){ s[j]<-sum(v[,j])} Means<-data.frame(Means,std=sds[,2],r=nn[,2],medians) names(Means)[1:2]<-c(name.t,name.y) means<-Means[,c(1:2,4)] rownames(Means)<-Means[,1] Means<-Means[,-1] means[,2]<-s rs<-array(0,m[2]) rs<-s-m[1]*(m[2]+1)/2 T1<-12*t(rs)%*%rs/(m[1]*m[2]*(m[2]+1)) T2<-(m[1]-1)*T1/(m[1]*(m[2]-1)-T1) if(console){ cat("\nStudy:",main,"\n\n") cat(paste(name.t,",",sep="")," Sum of the ranks\n\n") print(data.frame(row.names = means[,1], means[,-1])) cat("\nFriedman") cat("\n===============")} A1<-0 for (i in 1:m[1]) A1 <- A1 + t(v[i,])%*%v[i,] DFerror <-(m[1]-1)*(m[2]-1) Tprob<-qt(1-alpha/2,DFerror) LSD<-as.numeric(Tprob*sqrt(2*(m[1]*A1-t(s)%*%s)/DFerror)) C1 <-m[1]*m[2]*(m[2]+1)^2/4 T1.aj <-(m[2]-1)*(t(s)%*%s-m[1]*C1)/(A1-C1) T2.aj <-(m[1]-1)*T1.aj/(m[1]*(m[2]-1)-T1.aj) p.value<-1-pchisq(T1.aj,m[2]-1) p.noadj<-1-pchisq(T1,m[2]-1) PF<-1-pf(T2.aj, ntr-1, (ntr-1)*(nr-1) ) if(console){ cat("\nAdjusted for ties") cat("\nCritical Value:",T1.aj) cat("\nP.Value Chisq:",p.value) cat("\nF Value:",T2.aj) cat("\nP.Value F:",PF,"\n") cat("\nPost Hoc Analysis\n") } statistics<-data.frame(Chisq=T1.aj,Df=ntr-1,p.chisq=p.value,F=T2.aj,DFerror=DFerror,p.F=PF,t.value=Tprob,LSD) if ( group & length(nr) == 1 & console){ cat("\nAlpha:",alpha,"; DF Error:",DFerror) cat("\nt-Student:",Tprob) cat("\nLSD:", LSD,"\n") } if ( group & length(nr) != 1 & console) cat("\nGroups according to probability of treatment differences and alpha level(",alpha,")\n") if ( length(nr) != 1) statistics<-data.frame(Chisq=T1.aj,Df=ntr-1,p.chisq=p.value,F=T2.aj,DFerror=DFerror,p.F=PF) comb <-utils::combn(ntr,2) nn<-ncol(comb) dif<-rep(0,nn) pvalue<-rep(0,nn) LCL<-dif UCL<-dif sig<-NULL LSD<-rep(0,nn) stat<-rep("ns",nn) for (k in 1:nn) { i<-comb[1,k] j<-comb[2,k] dif[k]<-s[comb[1,k]]-s[comb[2,k]] sdtdif<- sqrt(2*(m[1]*A1-t(s)%*%s)/DFerror) pvalue[k]<- round(2*(1-pt(abs(dif[k])/sdtdif,DFerror)),4) LSD[k]<-round(Tprob*sdtdif,2) LCL[k] <- dif[k] - LSD[k] UCL[k] <- dif[k] + LSD[k] sig[k]<-" " if (pvalue[k] <= 0.001) sig[k]<-"***" else if (pvalue[k] <= 0.01) sig[k]<-"**" else if (pvalue[k] <= 0.05) sig[k]<-"*" else if (pvalue[k] <= 0.1) sig[k]<-"." } if(!group){ tr.i <- means[comb[1, ],1] tr.j <- means[comb[2, ],1] comparison<-data.frame("difference" = dif, pvalue=pvalue,"signif."=sig,LCL,UCL) rownames(comparison)<-paste(tr.i,tr.j,sep=" - ") if(console){cat("\nComparison between treatments\nSum of the ranks\n\n") print(comparison)} groups=NULL } if (group) { Q<-matrix(1,ncol=ntr,nrow=ntr) p<-pvalue k<-0 for(i in 1:(ntr-1)){ for(j in (i+1):ntr){ k<-k+1 Q[i,j]<-p[k] Q[j,i]<-p[k] } } groups <- ordenacao(means[, 1], means[, 2],alpha, Q,console) names(groups)[1]<-"Sum of ranks" if(console) { cat("\nTreatments with the same letter are not significantly different.\n\n") print(groups) } comparison<-NULL } parameters<-data.frame(test="Friedman",name.t=name.t,ntr = ntr,alpha=alpha) rownames(parameters)<-" " rownames(statistics)<-" " Means<-data.frame(rankSum=means[,2],Means) Means<-Means[,c(2,1,3:9)] output<-list(statistics=statistics,parameters=parameters, means=Means,comparison=comparison,groups=groups) class(output)<-"group" invisible(output) } fried=friedman(bloco,trat,response,alpha=alpha.t) cat(green(bold("\n\n-----------------------------------------------------------------\n"))) cat(green(italic("Statistics"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) print(fried$statistics) cat(green(bold("\n\n-----------------------------------------------------------------\n"))) cat(green(italic("Parameters"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) print(fried$parameters) cat(green(bold("\n\n-----------------------------------------------------------------\n"))) cat(green(italic("Multiple Comparison Test"))) cat(green(bold("\n-----------------------------------------------------------------\n"))) saida=cbind(fried$means[,c(1,3)],fried$groups[rownames(fried$means),]) colnames(saida)=c("Mean","SD","Rank","Groups") print(saida) dadosm=data.frame(fried$means,fried$groups[rownames(fried$means),]) dadosm$trats=factor(rownames(dadosm),levels = unique(trat)) dadosm$media=tapply(response,trat,mean, na.rm=TRUE)[rownames(fried$means)] if(point=="mean_sd"){dadosm$std=tapply(response,trat,sd, na.rm=TRUE)[rownames(fried$means)]} if(point=="mean_se"){dadosm$std=tapply(response,trat,sd, na.rm=TRUE)/ sqrt(tapply(response,trat,length))[rownames(fried$means)]} dadosm$limite=dadosm$response+dadosm$std dadosm$letra=paste(format(dadosm$response,digits = dec),dadosm$groups) if(addmean==TRUE){dadosm$letra=paste(format(dadosm$response,digits = dec),dadosm$groups)} if(addmean==FALSE){dadosm$letra=dadosm$groups} dadosm=dadosm[unique(trat),] trats=dadosm$trats limite=dadosm$limite media=dadosm$media std=dadosm$std letra=dadosm$letra if(geom=="bar"){grafico=ggplot(dadosm,aes(x=trats, y=response)) if(fill=="trat"){grafico=grafico+ geom_col(aes(fill=trats),color=1)} else{grafico=grafico+ geom_col(aes(fill=trats),fill=fill,color=1)} if(errorbar==TRUE){grafico=grafico+ geom_text(aes(y=media+sup+if(sup<0){-std}else{std},label=letra), family=family,size=labelsize,angle=angle.label, hjust=hjust)} if(errorbar==FALSE){grafico=grafico+ geom_text(aes(y=media+sup,label=letra),size=labelsize,family=family,angle=angle.label, hjust=hjust)} if(errorbar==TRUE){grafico=grafico+ geom_errorbar(aes(ymin=response-std, ymax=response+std), color="black", width=0.3)}} if(geom=="point"){grafico=ggplot(dadosm, aes(x=trats, y=response)) if(errorbar==TRUE){grafico=grafico+ geom_text(aes(y=media+sup+if(sup<0){-std}else{std},label=letra), family=family,size=labelsize,angle=angle.label, hjust=hjust)} if(errorbar==FALSE){grafico=grafico+ geom_text(aes(y=media+sup,label=letra),size=labelsize,family=family,angle=angle.label, hjust=hjust)} if(errorbar==TRUE){grafico=grafico+ geom_errorbar(aes(ymin=response-std, ymax=response+std), color="black", width=0.3)} if(fill=="trat"){grafico=grafico+ geom_point(aes(color=trats),size=5)} else{grafico=grafico+ geom_point(aes(color=trats),fill="gray",pch=21,color="black",size=5)}} if(geom=="box"){ datam1=data.frame(trats=factor(trat,levels = unique(as.character(trat))),response) dadosm2=data.frame(fried$means) dadosm2$trats=factor(rownames(dadosm),levels = unique(trat)) dadosm2$limite=dadosm2$response+dadosm2$std dadosm2$letra=paste(format(dadosm$response,digits = dec), dadosm$groups) dadosm2=dadosm2[unique(as.character(trat)),] trats=dadosm2$trats limite=dadosm2$limite letra=dadosm2$letra stat_box=ggplot(datam1,aes(x=trats,y=response))+geom_boxplot() superior=ggplot_build(stat_box)$data[[1]]$ymax dadosm2$superior=superior+sup grafico=ggplot(datam1,aes(x=trats, y=response)) if(fill=="trat"){grafico=grafico+ geom_boxplot(aes(fill=trats))} else{grafico=grafico+ geom_boxplot(aes(fill=trats),fill=fill)} grafico=grafico+ geom_text(data=dadosm2, aes(y=superior, label=letra),family=family,size=labelsize,angle=angle.label, hjust=hjust)} grafico=grafico+theme+ ylab(ylab)+ xlab(xlab)+ theme(text = element_text(size=textsize,color="black",family=family), axis.text = element_text(size=textsize,color="black",family=family), axis.title = element_text(size=textsize,color="black",family=family), legend.position = "none") if(angle !=0){grafico=grafico+theme(axis.text.x=element_text(hjust = 1.01, angle = angle))} } if(quali==TRUE){print(grafico)} grafico=list(grafico) }
/scratch/gouwar.j/cran-all/cranData/AgroTech/R/dbc_analysis.R