code
stringlengths
1
13.8M
FactoFAMD <- function() { nom.correct<-function(text, liste=NULL) { text<-chartr("^\ ", "...", text) if(!is.null(liste)) { while(text %in% liste) text<-paste(text, ".bis", sep="") } return(text) } top<-tktoplevel(borderwidth=10) tkwm.title(top,.Facto_gettext("FAMD")) tkwm.geometry(top, "-50+50") font2<-tkfont.create(family="times",size=12,weight="bold") fontheading<-tkfont.create(family="times",size=11,weight="bold") donnee<-get(getRcmdr(".activeDataSet")) vars<-colnames(donnee) rows<-rownames(donnee) listFrame <- tkframe(top,borderwidth=2) lab1 = tklabel(listFrame,text=.Facto_gettext("Select quantitative variables"),fg="blue") lab2 = tklabel(listFrame,text=.Facto_gettext("Select factors"),fg="blue") lab3 = tklabel(listFrame,text=" ") tkgrid(lab1,lab3,lab2) tkgrid.configure(lab1,column=1, columnspan=2, sticky = "nw") tkgrid.configure(lab2,column=4, columnspan=2, sticky = "ne") tkgrid.configure(lab3,column=3, columnspan=1, sticky = "n") listdesc<-tklistbox(listFrame,selectmode="extended",exportselection=FALSE,yscrollcommand=function(...) tkset(scr,...)) scr <- tkscrollbar(listFrame,repeatinterval=5,command=function(...)tkyview(listdesc,...)) tkselection.set(listdesc,0) listfact<-tklistbox(listFrame,selectmode="extended",exportselection=FALSE,yscrollcommand=function(...) tkset(scrfact,...)) scrfact <- tkscrollbar(listFrame,repeatinterval=5,command=function(...)tkyview(listfact,...)) vars<-colnames(donnee) vars.fact = NULL vars.desc = NULL for (i in (1:ncol(donnee))){ if (is.numeric(donnee[,i])){ tkinsert(listdesc,"end",vars[i]) vars.desc = c(vars.desc,vars[i]) } else { vars.fact = c(vars.fact,vars[i]) tkinsert(listfact,"end",vars[i]) } } tkgrid(listdesc, scr,tklabel(listFrame,text=" "),listfact,scrfact,sticky = "nw") tkgrid.configure(scr, sticky = "wns", column=2, columnspan=1) tkgrid.configure(listdesc,sticky = "ew", column=1, columnspan=1) tkgrid.configure(scrfact,sticky = "wns", column=5, columnspan=1) tkgrid.configure(listfact,sticky = "ew", column=4, columnspan=1) Fillu.funct<-defmacro(label, firstLabel, expr= { env<-environment() variablefact<-NULL .FilluLabel<-tclVar(paste(firstLabel, "", sep=" ")) .factors<-Factors() OnFillu<-function() { if(length(.factors)==0) errorCondition(recall=NULL, message=.Facto_gettext("No Factor available")) FilluWin<-tktoplevel() tkwm.title(FilluWin,.Facto_gettext("Choice of supplementary factors")) FOK.funct<-function() { fact.select<-listfact.nom[as.numeric(tkcurselection(listfact))+1] if(length(fact.select)==0) { assign("variablefact", NULL, envir=env) tclvalue(.FilluLabel)<-paste(firstLabel, "", sep=" ") tkconfigure(Fillu.but, fg="black") tkdestroy(FilluWin) return() } assign("variablefact", fact.select, envir=env) tclvalue(.FilluLabel)<-paste(label, "", sep=" ") tkconfigure(Fillu.but, fg="blue") tkdestroy(FilluWin) } listfact<-tklistbox(FilluWin,selectmode="extended",exportselection="FALSE",yscrollcommand=function(...)tkset(scrfact,...)) scrfact <-tkscrollbar(FilluWin,repeatinterval=5,command=function(...)tkyview(listfact,...)) listfact.nom<-NULL indice<-0 for (i in (1:ncol(donnee))) { if (is.factor(donnee[,i])) { tkinsert(listfact,"end",vars[i]) listfact.nom<-c(listfact.nom,vars[i]) if(vars[i] %in% variablefact) tkselection.set(listfact, indice) indice<-indice+1 } } FOK.but<-tkbutton(FilluWin, text="OK", width=16,command=FOK.funct) tkgrid(tklabel(FilluWin, text="")) tkgrid(tklabel(FilluWin, text = .Facto_gettext("Select supplementary factor(s)"), fg = "blue"), column=1, columnspan = 1, sticky = "ew") tkgrid(listfact, scrfact, sticky = "nw") tkgrid.configure(scrfact, sticky = "ens", columnspan=1) tkgrid.configure(listfact, sticky = "ew", column=1, columnspan=1) tkgrid(tklabel(FilluWin, text="")) tkgrid(FOK.but, column=1,columnspan=1, sticky="ew") tkgrid(tklabel(FilluWin, text="")) tkgrid.columnconfigure(FilluWin,0, minsize=25) tkgrid.columnconfigure(FilluWin,2, minsize=25) } FilluFrame<-tkframe(IlluFrame) if(length(.factors)==0){ Fillu.but<-tkbutton(FilluFrame, text=.Facto_gettext("No factors available"), borderwidth=3) tkconfigure(Fillu.but, fg="grey") } else Fillu.but<-tkbutton(FilluFrame, textvariable=.FilluLabel, command=OnFillu, borderwidth=3) tkgrid(Fillu.but, sticky="ew") }) Dillu.funct<-defmacro(label, firstLabel, expr= { env<-environment() variableillu<-NULL .DilluLabel<-tclVar(paste(firstLabel, "", sep=" ")) OnDillu<-function() { DilluWin<-tktoplevel() tkwm.title(DilluWin,.Facto_gettext("Select supplementary quantitative variables")) DOK.funct<-function() { vsup.select<-listvar.nom[as.numeric(tkcurselection(listvar))+1] if(length(vsup.select)==0) { assign("variableillu", NULL, envir=env) tclvalue(.DilluLabel)<-paste(firstLabel, "", sep=" ") tkconfigure(Dillu.but, fg="black") tkdestroy(DilluWin) return() } assign("variableillu", vsup.select, envir=env) tclvalue(.DilluLabel)<-paste(label, "", sep=" ") tkconfigure(Dillu.but, fg="blue") tkdestroy(DilluWin) } listvar<-tklistbox(DilluWin,selectmode="extended",exportselection="FALSE",yscrollcommand=function(...)tkset(scrvar,...)) scrvar <-tkscrollbar(DilluWin,repeatinterval=5,command=function(...)tkyview(listvar,...)) listvar.nom<-NULL indice<-0 for (i in (1:ncol(donnee))) { if (is.numeric(donnee[,i])) { tkinsert(listvar,"end",vars[i]) listvar.nom<-c(listvar.nom,vars[i]) if(vars[i] %in% variableillu) tkselection.set(listvar, indice) indice<-indice+1 } } DOK.but<-tkbutton(DilluWin, text="OK", width=16,command=DOK.funct) tkgrid(tklabel(DilluWin, text="")) tkgrid(tklabel(DilluWin, text = .Facto_gettext("Select supplementary quantitative variables"), fg = "blue"), column=1, columnspan = 1, sticky = "ew") tkgrid(listvar, scrvar, sticky = "nw") tkgrid.configure(scrvar, sticky = "ens", columnspan=1) tkgrid.configure(listvar, sticky = "ew", column=1, columnspan=1) tkgrid(tklabel(DilluWin, text="")) tkgrid(DOK.but, column=1,columnspan=1, sticky="ew") tkgrid(tklabel(DilluWin, text="")) tkgrid.columnconfigure(DilluWin,0, minsize=25) tkgrid.columnconfigure(DilluWin,2, minsize=25) } DilluFrame<-tkframe(IlluFrame) if(length(listNumeric())==0){ Dillu.but<-tkbutton(DilluFrame, text=.Facto_gettext("No quantitative variable available"), borderwidth=3) tkconfigure(Dillu.but, fg="grey") } else Dillu.but<-tkbutton(DilluFrame, textvariable=.DilluLabel, command=OnDillu, borderwidth=3) tkgrid(Dillu.but, sticky="ew") }) Iillu.funct<-defmacro(label, firstLabel, expr= { env<-environment() individuillu<-NULL .IilluLabel<-tclVar(paste(firstLabel, "", sep=" ")) OnIillu<-function() { IilluWin<-tktoplevel() tkwm.title(IilluWin,.Facto_gettext("Select supplementary individual(s)")) IOK.funct<-function() { ind.select<-rows[as.numeric(tkcurselection(listind))+1] if(length(ind.select)==0) { assign("individuillu", NULL, envir=env) tclvalue(.IilluLabel)<-paste(firstLabel, "", sep=" ") tkconfigure(Iillu.but, fg="black") tkdestroy(IilluWin) return() } assign("individuillu", ind.select, envir=env) tclvalue(.IilluLabel)<-paste(label, "", sep=" ") tkconfigure(Iillu.but, fg="blue") tkdestroy(IilluWin) } listind<-tklistbox(IilluWin,selectmode="extended",exportselection="FALSE",yscrollcommand=function(...)tkset(scrind,...)) scrind <-tkscrollbar(IilluWin,repeatinterval=5,command=function(...)tkyview(listind,...)) indice<-0 for (i in (1:nrow(donnee))) { tkinsert(listind,"end",rows[i]) if(rows[i] %in% individuillu) tkselection.set(listind, indice) indice<-indice+1 } IOK.but<-tkbutton(IilluWin, text="OK", width=16,command=IOK.funct) tkgrid(tklabel(IilluWin, text="")) tkgrid(tklabel(IilluWin, text = .Facto_gettext("Select supplementary individual(s)"), fg = "blue"), column=1, columnspan = 1, sticky = "ew") tkgrid(listind, scrind, sticky = "nw") tkgrid.configure(scrind, sticky = "ens", columnspan=1) tkgrid.configure(listind, sticky = "ew", column=1, columnspan=1) tkgrid(tklabel(IilluWin, text="")) tkgrid(IOK.but, column=1,columnspan=1, sticky="ew") tkgrid(tklabel(IilluWin, text="")) tkgrid.columnconfigure(IilluWin,0, minsize=25) tkgrid.columnconfigure(IilluWin,2, minsize=25) } IilluFrame<-tkframe(IlluFrame) Iillu.but<-tkbutton(IilluFrame, textvariable=.IilluLabel, command=OnIillu, borderwidth=3) tkgrid(Iillu.but, sticky="ew") }) Reinitializ.funct<-function() { tkdestroy(top) FactoFAMD() } Sortie.funct<-defmacro(label, firstLabel, expr= { env<-environment() compteur.sortie<-0 Rpropre<-FALSE RFichier <- "" Rgroupe<-FALSE Rindividu<-FALSE Rindsup<-FALSE Rquanti<-FALSE Rquantisup<-FALSE Rquali<-FALSE Rqualisup<-FALSE Rdescdim<-FALSE .SortieLabel<-tclVar(paste(firstLabel, "", sep=" ")) OnSortie<-function() { SortieWin<-tktoplevel() tkwm.title(SortieWin,.Facto_gettext("Output options")) onOK.sortie<-function() { assign("compteur.sortie", compteur.sortie+1, envir=env) if(compteur.sortie>0) tclvalue(.SortieLabel)<-paste(label, "", sep=" ") tkconfigure(Sortie.but, fg="blue") if(tclvalue(eigValue)=="1") assign("Rpropre", TRUE, envir=env) else assign("Rpropre", FALSE, envir=env) if(tclvalue(groupeValue)=="1") assign("Rgroupe", TRUE, envir=env) else assign("Rgroupe", FALSE, envir=env) if(tclvalue(indValue)=="1") assign("Rindividu", TRUE, envir=env) else assign("Rindividu", FALSE, envir=env) if(tclvalue(ind.sup.Value)=="1") assign("Rindsup", TRUE, envir=env) else assign("Rindsup", FALSE, envir=env) if(tclvalue(quantiValue)=="1") assign("Rquanti", TRUE, envir=env) else assign("Rquanti", FALSE, envir=env) if(tclvalue(quantisupValue)=="1") assign("Rquantisup", TRUE, envir=env) else assign("Rquantisup", FALSE, envir=env) if(tclvalue(qualiValue)=="1") assign("Rquali", TRUE, envir=env) else assign("Rquali", FALSE, envir=env) if(tclvalue(qualisupValue)=="1") assign("Rqualisup", TRUE, envir=env) else assign("Rqualisup", FALSE, envir=env) if(tclvalue(descdimValue)=="1") assign("Rdescdim", TRUE, envir=env) else assign("Rdescdim", FALSE, envir=env) if (tclvalue(Fichier)=="") assign("RFichier", NULL, envir=env) assign("RFichier", tclvalue(Fichier), envir=env) tkdestroy(SortieWin) } eig.lab <-tklabel(SortieWin, text=.Facto_gettext("Eigenvalues")) eig.check <- tkcheckbutton(SortieWin) if(Rpropre) eigValue <- tclVar("1") else eigValue <- tclVar("0") tkconfigure(eig.check,variable=eigValue) groupe.lab <-tklabel(SortieWin, text=.Facto_gettext("Results for the variables")) groupe.check <- tkcheckbutton(SortieWin) if(Rgroupe) groupeValue <- tclVar("1") else groupeValue <- tclVar("0") tkconfigure(groupe.check,variable=groupeValue) ind.lab<-tklabel(SortieWin,text=.Facto_gettext("Results for the active individuals")) ind.check <- tkcheckbutton(SortieWin) if(Rindividu) indValue <- tclVar("1") else indValue <- tclVar("0") tkconfigure(ind.check,variable=indValue) ind.sup.lab<-tklabel(SortieWin,text=.Facto_gettext("Results for the supplementary individuals")) ind.sup.check <- tkcheckbutton(SortieWin) if(Rindsup) ind.sup.Value <- tclVar("1") else ind.sup.Value <- tclVar("0") tkconfigure(ind.sup.check,variable=ind.sup.Value) quanti.lab<-tklabel(SortieWin,text=.Facto_gettext("Results of the quantitative variables")) quanti.check <- tkcheckbutton(SortieWin) if(Rquanti) quantiValue <- tclVar("1") else quantiValue <- tclVar("0") tkconfigure(quanti.check,variable=quantiValue) quantisup.lab<-tklabel(SortieWin,text=.Facto_gettext("Results of the supplementary quantitative variables")) quantisup.check <- tkcheckbutton(SortieWin) if(Rquantisup) quantisupValue <- tclVar("1") else quantisupValue <- tclVar("0") tkconfigure(quantisup.check,variable=quantisupValue) quali.lab<-tklabel(SortieWin,text=.Facto_gettext("Results of the qualitative variables")) quali.check <- tkcheckbutton(SortieWin) if(Rquali) qualiValue <- tclVar("1") else qualiValue <- tclVar("0") tkconfigure(quali.check,variable=qualiValue) qualisup.lab<-tklabel(SortieWin,text=.Facto_gettext("Results of the supplementary qualitative variables")) qualisup.check <- tkcheckbutton(SortieWin) if(Rqualisup) qualisupValue <- tclVar("1") else qualisupValue <- tclVar("0") tkconfigure(qualisup.check,variable=qualisupValue) descdim.lab<-tklabel(SortieWin, text=.Facto_gettext("Description of the dimensions")) descdim.check<-tkcheckbutton(SortieWin) if(Rdescdim) descdimValue<-tclVar("1") else descdimValue<-tclVar("0") tkconfigure(descdim.check,variable=descdimValue) RFichierFrame<-tkframe(SortieWin,borderwidth=2) if (is.null(RFichier)) Fichier <- tclVar("") else Fichier<-tclVar(RFichier) Fichier.entry <-tkentry(RFichierFrame,width="40",textvariable=Fichier) tkgrid(tklabel(RFichierFrame,text=.Facto_gettext("Print results on a 'csv' file")),Fichier.entry) SortieOK.but<-tkbutton(SortieWin,text="OK",width=16,command=onOK.sortie) tkgrid(tklabel(SortieWin, text = .Facto_gettext("Select output options"), fg ="blue"), columnspan = 2, sticky = "w") tkgrid(tklabel(SortieWin, text = " ")) tkgrid(eig.lab,eig.check,sticky="w") tkgrid(groupe.lab,groupe.check,sticky="w") tkgrid(ind.lab,ind.check,sticky="w") if (!is.null(individuillu)) tkgrid(ind.sup.lab,ind.sup.check,sticky="w") tkgrid(quanti.lab,quanti.check,sticky="w") if (!is.null(variableillu)) tkgrid(quantisup.lab,quantisup.check,sticky="w") tkgrid(quali.lab,quali.check,sticky="w") if (!is.null(variablefact)) tkgrid(qualisup.lab,qualisup.check,sticky="w") tkgrid(descdim.lab,descdim.check,sticky="w") tkgrid(tklabel(SortieWin, text = " ")) tkgrid(RFichierFrame) tkgrid(SortieOK.but) tkgrid(tklabel(SortieWin, text = " ")) } SortieFrame<-tkframe(IlluFrame) Sortie.but<-tkbutton(SortieFrame, textvariable=.SortieLabel, command=OnSortie, borderwidth=3) tkgrid(Sortie.but, sticky="ew") }) PLOT.FAMD<-defmacro(label, firstLabel, expr= { env<-environment() compteur.graph<-0 .PlotLabel<-tclVar(paste(firstLabel, "", sep=" ")) Gchoix<-TRUE GTitle<-NULL Gcol.var<-Gcol.var.tmp<-"red" Gcol.quanti.sup<-Gcol.quanti.sup.tmp<-"darkred" Gcol.quali<-Gcol.quali.tmp<-"green" Gcol.quali.sup<-Gcol.quali.sup.tmp<-"darkgreen" GAxeGrpe<-c(1,2) Glabel<-TRUE Rchoix<-TRUE RTitle<-NULL Rlabel.indMoy<-TRUE Rlabel.quali<-TRUE Rhabillage<-"none" Rinvisible<-NULL RXlimInd<-NULL RYlimInd<-NULL Wchoix=TRUE WTitle<-NULL WAxeVar<-c(1,2) Wlabel.var<-TRUE Wcol.quanti.sup<-Wcol.quanti.sup.tmp<-"blue" Wcol.var<-Wcol.var.tmp<-"black" Winvisible<-NULL Wlim.cos<-0. OnPlot<-function() { PlotWin<-tktoplevel() tkwm.title(PlotWin,.Facto_gettext("Graphical options")) tkwm.geometry(PlotWin, "-100+50") PlotWin2<-tkframe(PlotWin) onOKsub<-function() { assign("compteur.graph", compteur.graph+1, envir=env) if(compteur.graph>0) tclvalue(.PlotLabel)<-paste(label, .Facto_gettext(""), sep=" ") tkconfigure(Plot.but, fg="blue") if(tclvalue(grpe.check.value)==1) assign("Gchoix", TRUE, envir=env) else assign("Gchoix", FALSE, envir=env) if(Gchoix) { if (tclvalue(GTitre)==" ") assign("GTitle", NULL, envir=env) assign("GTitle", tclvalue(GTitre), envir=env) assign("Gcol.var", Gcol.var.tmp, envir=env) assign("Gcol.quanti.sup", Gcol.quanti.sup.tmp, envir=env) assign("Gcol.quali", Gcol.quali.tmp, envir=env) assign("Gcol.quali.sup", Gcol.quali.sup.tmp, envir=env) label.tmp.grpe<-tclvalue(label.grpe.checkValue) if(label.tmp.grpe==1) assign("Glabel", TRUE, envir=env) else assign("Glabel", FALSE, envir=env) } if(tclvalue(var.check.value)==1) assign("Wchoix", TRUE, envir=env) else assign("Wchoix", FALSE, envir=env) if(Wchoix) { if (tclvalue(WTitre)==" ") assign("WTitle", NULL, envir=env) assign("WTitle", tclvalue(WTitre), envir=env) assign("Wlim.cos", tclvalue(WlimCosValue), envir=env) label.tmp.var<-tclvalue(label.var.checkValue) if(label.tmp.var==1) assign("Wlabel.var", TRUE, envir=env) else assign("Wlabel.var", FALSE, envir=env) assign("Wcol.var", Wcol.var.tmp, envir=env) assign("Wcol.quanti.sup", Wcol.quanti.sup.tmp, envir=env) if(tclvalue(inv.Value)=="aucun") assign("Winvisible", NULL, envir=env) else assign("Winvisible", tclvalue(inv.Value), envir=env) } if(tclvalue(ind.check.value)==1) assign("Rchoix", TRUE, envir=env) else assign("Rchoix", FALSE, envir=env) if(Rchoix) { if (tclvalue(Titre)==" ") assign("RTitle", NULL, envir=env) assign("RTitle", tclvalue(Titre), envir=env) label.tmp.indMoy<-tclvalue(label.indMoy.checkValue) label.tmp.quali<-tclvalue(label.quali.checkValue) if(label.tmp.indMoy==1) assign("Rlabel.indMoy", TRUE, envir=env) else assign("Rlabel.indMoy", FALSE, envir=env) if(label.tmp.quali==1) assign("Rlabel.quali", TRUE, envir=env) else assign("Rlabel.quali", FALSE, envir=env) habillage.tmp<-listgraph.nom[as.numeric(tkcurselection(listgraph))+1] if(length(habillage.tmp)==0) assign("Rhabillage","none", envir=env) else assign("Rhabillage", habillage.tmp, envir=env) if(tclvalue(XlimIndMin)=="" | tclvalue(XlimIndMax)=="") assign("RXlimInd", NULL, envir=env) else assign("RXlimInd", c(as.numeric(tclvalue(XlimIndMin)), as.numeric(tclvalue(XlimIndMax))), envir=env) if(tclvalue(YlimIndMin)=="" | tclvalue(YlimIndMax)=="") assign("RYlimInd", NULL, envir=env) else assign("RYlimInd", c(as.numeric(tclvalue(YlimIndMin)), as.numeric(tclvalue(YlimIndMax))), envir=env) inv.ind.tmp<-tclvalue(inv.ind.checkValue) inv.ind.sup.tmp<-tclvalue(inv.ind.sup.checkValue) inv.quali.tmp<-tclvalue(inv.quali.checkValue) assign("Rinvisible", NULL, envir=env) if(inv.ind.tmp=="1") assign("Rinvisible", c(Rinvisible, "ind"), envir=env) if(inv.ind.sup.tmp=="1") assign("Rinvisible", c(Rinvisible, "ind.sup"), envir=env) if(inv.quali.tmp=="1") assign("Rinvisible", c(Rinvisible, "quali"), envir=env) } tkdestroy(PlotWin) } PlotGrpeFrame<-tkframe(PlotWin2, borderwidth=5, relief="groove") GchoixFrame<-tkframe(PlotGrpeFrame,borderwidth=2) grpe.check<-tkcheckbutton(GchoixFrame) if(Gchoix) grpe.check.value<-tclVar("1") else grpe.check.value<-tclVar("0") tkconfigure(grpe.check, variable=grpe.check.value) tkgrid(tklabel(GchoixFrame, text=.Facto_gettext("Graph of all the variables"), font=font2),grpe.check) tkgrid(tklabel(GchoixFrame, text=" ")) GTitleFrame<-tkframe(PlotGrpeFrame,borderwidth=2) if (is.null(GTitle)) GTitre <- tclVar(" ") else GTitre<-tclVar(GTitle) GTitre.entry <-tkentry(GTitleFrame,width="40",textvariable=GTitre) tkgrid(tklabel(GTitleFrame,text=.Facto_gettext("Title of the graph")),GTitre.entry) GcolFrame<-tkframe(PlotGrpeFrame,borderwidth=2) Gcol.var.value <- Gcol.var canvas.var <- tkcanvas(GcolFrame,width="80",height="25",bg=Gcol.var.value) ChangeColor.var <- function() { Gcol.var.value<-tclvalue(tcl("tk_chooseColor",initialcolor=Gcol.var.value,title=.Facto_gettext("Choose a color"))) if (nchar(Gcol.var.value)>0) { tkconfigure(canvas.var,bg=Gcol.var.value) assign("Gcol.var.tmp", Gcol.var.value, envir=env) } } ChangeColor.var.button <- tkbutton(GcolFrame,text=.Facto_gettext("Change Color"),command=ChangeColor.var) tkgrid(tklabel(GcolFrame, text=.Facto_gettext("Color of the quantitative variables")),canvas.var,ChangeColor.var.button) Gcol.quanti.sup.value<-Gcol.quanti.sup canvas.quanti.sup <- tkcanvas(GcolFrame,width="80",height="25",bg=Gcol.quanti.sup.value) ChangeColor.quanti.sup <- function() { Gcol.quanti.sup.value<-tclvalue(tcl("tk_chooseColor",initialcolor=Gcol.quanti.sup.value,title=.Facto_gettext("Choose a color"))) if (nchar(Gcol.quanti.sup.value)>0) { tkconfigure(canvas.quanti.sup,bg=Gcol.quanti.sup.value) assign("Gcol.quanti.sup.tmp", Gcol.quanti.sup.value, envir=env) } } ChangeColor.quanti.sup.button <- tkbutton(GcolFrame,text=.Facto_gettext("Change Color"),command=ChangeColor.quanti.sup) if(!is.null(variableillu)) tkgrid(tklabel(GcolFrame, text=.Facto_gettext("color for supplementary quantitative variables")),canvas.quanti.sup,ChangeColor.quanti.sup.button) Gcol.quali.value<-Gcol.quali canvas.quali <- tkcanvas(GcolFrame,width="80",height="25",bg=Gcol.quali.value) ChangeColor.quali <- function() { Gcol.quali.value<-tclvalue(tcl("tk_chooseColor",initialcolor=Gcol.quali.value,title=.Facto_gettext("Choose a color"))) if (nchar(Gcol.quali.value)>0) { tkconfigure(canvas.quali,bg=Gcol.quali.value) assign("Gcol.quali.tmp", Gcol.quali.value, envir=env) } } ChangeColor.quali.button <- tkbutton(GcolFrame,text=.Facto_gettext("Change Color"),command=ChangeColor.quali) tkgrid(tklabel(GcolFrame, text=.Facto_gettext("color for qualitative variables")),canvas.quali,ChangeColor.quali.button) Gcol.quali.sup.value<-Gcol.quali.sup canvas.quali.sup <- tkcanvas(GcolFrame,width="80",height="25",bg=Gcol.quali.sup.value) ChangeColor.quali.sup <- function() { Gcol.quali.sup.value<-tclvalue(tcl("tk_chooseColor",initialcolor=Gcol.quali.sup.value,title=.Facto_gettext("Choose a color"))) if (nchar(Gcol.quali.sup.value)>0) { tkconfigure(canvas.quali.sup,bg=Gcol.quali.sup.value) assign("Gcol.quali.sup.tmp", Gcol.quali.sup.value, envir=env) } } ChangeColor.quali.sup.button <- tkbutton(GcolFrame,text=.Facto_gettext("Change Color"),command=ChangeColor.quali.sup) if(!is.null(variablefact)) tkgrid(tklabel(GcolFrame, text=.Facto_gettext("color for supplementary qualitative variables")),canvas.quali.sup,ChangeColor.quali.sup.button) GlabelFrame<-tkframe(PlotGrpeFrame,borderwidth=2) label.grpe.check<-tkcheckbutton(GlabelFrame) if (Glabel) label.grpe.checkValue<-tclVar("1") else label.grpe.checkValue<-tclVar("0") tkconfigure(label.grpe.check, variable=label.grpe.checkValue) tkgrid(tklabel(GlabelFrame, text=.Facto_gettext("Labels for the variables")),label.grpe.check) tkgrid(GchoixFrame) tkgrid(GTitleFrame) tkgrid(GcolFrame) tkgrid(GlabelFrame) tkgrid(tklabel(PlotGrpeFrame, text=" ")) PlotVarFrame<-tkframe(PlotWin2, borderwidth=5, relief="groove") WchoixFrame<-tkframe(PlotVarFrame,borderwidth=2) var.check<-tkcheckbutton(WchoixFrame) if(Wchoix) var.check.value<-tclVar("1") else var.check.value<-tclVar("0") tkconfigure(var.check, variable=var.check.value) tkgrid(tklabel(WchoixFrame, text=.Facto_gettext("Graph of the quantitative variables"), font=font2),var.check) tkgrid(tklabel(WchoixFrame, text=" ")) WTitleFrame<-tkframe(PlotVarFrame,borderwidth=2) if (is.null(WTitle)) WTitre <- tclVar(" ") else WTitre<-tclVar(WTitle) WTitre.entry <-tkentry(WTitleFrame,width="40",textvariable=WTitre) tkgrid(tklabel(WTitleFrame,text=.Facto_gettext("Title of the graph")),WTitre.entry) WcosFrame<-tkframe(PlotVarFrame,borderwidth=2) WlimCosValue<-tclVar(paste(Wlim.cos)) WlimCos.entry<-tkentry(WcosFrame, width=5, textvariable=WlimCosValue) tkgrid(tklabel(WcosFrame,text=.Facto_gettext("Draw variables with a cos2 >:")),WlimCos.entry) WlabelFrame<-tkframe(PlotVarFrame,borderwidth=2) label.var.check<-tkcheckbutton(WlabelFrame) if (Wlabel.var) label.var.checkValue<-tclVar("1") else label.var.checkValue<-tclVar("0") tkconfigure(label.var.check, variable=label.var.checkValue) tkgrid(tklabel(WlabelFrame, text=.Facto_gettext("Labels for the variables")),label.var.check) WcolFrame<-tkframe(PlotVarFrame,borderwidth=2) Wcol.var.value <- Wcol.var Wcanvas.var <- tkcanvas(WcolFrame,width="80",height="25",bg=Wcol.var.value) WChangeColor.var <- function() { Wcol.var.value<-tclvalue(tcl("tk_chooseColor",initialcolor=Wcol.var.value,title=.Facto_gettext("Choose a color"))) if (nchar(Wcol.var.value)>0) { tkconfigure(Wcanvas.var,bg=Wcol.var.value) assign("Wcol.var.tmp", Wcol.var.value, envir=env) } } WChangeColor.var.button <- tkbutton(WcolFrame,text=.Facto_gettext("Change Color"),command=WChangeColor.var) tkgrid(tklabel(WcolFrame, text=.Facto_gettext("Color of the active variables")),Wcanvas.var,WChangeColor.var.button) Wcol.quanti.sup.value<-Wcol.quanti.sup Wcanvas.quanti.sup <- tkcanvas(WcolFrame,width="80",height="25",bg=Wcol.quanti.sup.value) WChangeColor.quanti.sup <- function() { Wcol.quanti.sup.value<-tclvalue(tcl("tk_chooseColor",initialcolor=Wcol.quanti.sup.value,title=.Facto_gettext("Choose a color"))) if (nchar(Wcol.quanti.sup.value)>0) { tkconfigure(Wcanvas.quanti.sup,bg=Wcol.quanti.sup.value) assign("Wcol.quanti.sup.tmp", Wcol.quanti.sup.value, envir=env) } } WChangeColor.quanti.sup.button <- tkbutton(WcolFrame,text=.Facto_gettext("Change Color"),command=WChangeColor.quanti.sup) if(!is.null(variableillu)) tkgrid(tklabel(WcolFrame, text=.Facto_gettext("color for supplementary variables")),Wcanvas.quanti.sup,WChangeColor.quanti.sup.button) WinvisibleFrame<-tkframe(PlotVarFrame,borderwidth=2) inv.aucun.check<-tkradiobutton(WinvisibleFrame) inv.act.check<-tkradiobutton(WinvisibleFrame) inv.sup.check<-tkradiobutton(WinvisibleFrame) if(is.null(Winvisible)) inv.Value<-tclVar("aucun") else inv.Value<-tclVar(Winvisible) tkconfigure(inv.aucun.check,variable=inv.Value,value="aucun") tkconfigure(inv.act.check,variable=inv.Value, value="actif") tkconfigure(inv.sup.check,variable=inv.Value, value="sup") tkgrid(tklabel(WinvisibleFrame, text=.Facto_gettext("Hide some elements:")), columnspan=6, sticky="w") tkgrid(tklabel(WinvisibleFrame, text="None"),inv.aucun.check, tklabel(WinvisibleFrame, text=.Facto_gettext("active variables")),inv.act.check, tklabel(WinvisibleFrame, text=.Facto_gettext("supplementary variables")),inv.sup.check, sticky="w") tkgrid(WchoixFrame) tkgrid(WTitleFrame) tkgrid(WcolFrame) tkgrid(WcosFrame) tkgrid(WlabelFrame) tkgrid(WinvisibleFrame) tkgrid(tklabel(PlotVarFrame, text=" ")) PlotIndFrame<-tkframe(PlotWin, borderwidth=5, relief="groove") RchoixFrame<-tkframe(PlotIndFrame,borderwidth=2) ind.check<-tkcheckbutton(RchoixFrame) if(Rchoix) ind.check.value<-tclVar("1") else ind.check.value<-tclVar("0") tkconfigure(ind.check, variable=ind.check.value) tkgrid(tklabel(RchoixFrame, text=.Facto_gettext("Graph of the individuals"), font=font2),ind.check) tkgrid(tklabel(RchoixFrame, text=" ")) RTitleFrame<-tkframe(PlotIndFrame,borderwidth=2) if (is.null(RTitle)) Titre <- tclVar(" ") else Titre<-tclVar(RTitle) Titre.entry <-tkentry(RTitleFrame,width="40",textvariable=Titre) tkgrid(tklabel(RTitleFrame,text=.Facto_gettext("Title of the graph")),Titre.entry) RlabelFrame<-tkframe(PlotIndFrame,borderwidth=2) label.indMoy.check<-tkcheckbutton(RlabelFrame) if (Rlabel.indMoy) label.indMoy.checkValue<-tclVar("1") else label.indMoy.checkValue<-tclVar("0") tkconfigure(label.indMoy.check, variable=label.indMoy.checkValue) tkgrid(tklabel(RlabelFrame, text=.Facto_gettext("Labels for the mean individuals")),label.indMoy.check) label.quali.check<-tkcheckbutton(RlabelFrame) if (Rlabel.quali) label.quali.checkValue<-tclVar("1") else label.quali.checkValue<-tclVar("0") tkconfigure(label.quali.check, variable=label.quali.checkValue) tkgrid(tklabel(RlabelFrame, text=.Facto_gettext("Labels for the factors")), label.quali.check) RhabillageFrame<-tkframe(PlotIndFrame,borderwidth=2) listgraph<-tklistbox(RhabillageFrame,height=4, selectmode="single",exportselection="FALSE",yscrollcommand=function(...) tkset(scrgraph,...)) scrgraph <-tkscrollbar(RhabillageFrame,repeatinterval=5,command=function(...)tkyview(listgraph,...)) listgraph.nom<-c("ind") tkinsert(listgraph,"end","by.individual") if(Rhabillage=="ind") tkselection.set(listgraph,0) indice<-1 nbauxli<-c(tclvalue(tkcurselection(listfact))) nbaux<-unlist(strsplit(nbauxli,"\\ ")) varaux = vars.fact[as.numeric(tkcurselection(listfact))+1] if (!is.null(variablefact)|(length(nbaux)>0)){ for (j in 1:ncol(donnee)){ if(vars[j] %in% c(variablefact,varaux)){ tkinsert(listgraph,"end",vars[j]) listgraph.nom<-c(listgraph.nom,vars[j]) if(Rhabillage==vars[j]) tkselection.set(listgraph, indice) indice<-indice+1 }} } tkgrid(tklabel(RhabillageFrame, text=.Facto_gettext("Select drawing for the individuals"))) tkgrid(listgraph, scrgraph, sticky = "nw") tkgrid.configure(scrgraph, sticky = "wns") tkgrid.configure(listgraph, sticky = "ew") RinvisibleFrame<-tkframe(PlotIndFrame,borderwidth=2) inv.ind.check<-tkcheckbutton(RinvisibleFrame) if ("ind" %in% Rinvisible) inv.ind.checkValue<-tclVar("1") else inv.ind.checkValue<-tclVar("0") inv.ind.sup.check<-tkcheckbutton(RinvisibleFrame) if ("ind.sup" %in% Rinvisible) inv.ind.sup.checkValue<-tclVar("1") else inv.ind.sup.checkValue<-tclVar("0") inv.quali.check<-tkcheckbutton(RinvisibleFrame) if ("quali" %in% Rinvisible) inv.quali.checkValue<-tclVar("1") else inv.quali.checkValue<-tclVar("0") tkconfigure(inv.ind.check, variable=inv.ind.checkValue) tkconfigure(inv.ind.sup.check, variable=inv.ind.sup.checkValue) tkconfigure(inv.quali.check, variable=inv.quali.checkValue) tkgrid(tklabel(RinvisibleFrame, text=.Facto_gettext("Hide some elements:")), columnspan=6, sticky="w") tkgrid(tklabel(RinvisibleFrame, text="ind"),inv.ind.check, tklabel(RinvisibleFrame, text="ind sup"),inv.ind.sup.check, tklabel(RinvisibleFrame, text="quali"),inv.quali.check, sticky="w") RlimFrame<-tkframe(PlotIndFrame,borderwidth=2) if(is.null(RXlimInd)) XlimIndMin<-tclVar("") else XlimIndMin<-tclVar(paste(RXlimInd[1])) XlimIndMin.entry <-tkentry(RlimFrame,width="5",textvariable=XlimIndMin) if (is.null(RXlimInd)) XlimIndMax<- tclVar("") else XlimIndMax<-tclVar(paste(RXlimInd[1])) XlimIndMax.entry <-tkentry(RlimFrame,width="5",textvariable=XlimIndMax) tkgrid(tklabel(RlimFrame,text=.Facto_gettext("x limits of the graph:")),XlimIndMin.entry, XlimIndMax.entry) if(is.null(RYlimInd)) YlimIndMin<- tclVar("") else YlimIndMin<-tclVar(paste(RYlimInd[1])) YlimIndMin.entry <-tkentry(RlimFrame,width="5",textvariable=YlimIndMin) if (is.null(RYlimInd)) YlimIndMax<- tclVar("") else YlimIndMax<-tclVar(paste(RYlimInd[2])) YlimIndMax.entry <-tkentry(RlimFrame,width="5",textvariable=YlimIndMax) tkgrid(tklabel(RlimFrame,text=.Facto_gettext("y limits of the graph:")),YlimIndMin.entry,YlimIndMax.entry) tkgrid(RchoixFrame) tkgrid(RTitleFrame) tkgrid(RlabelFrame) tkgrid(RinvisibleFrame) tkgrid(tklabel(PlotIndFrame, text=" ")) tkgrid(RhabillageFrame) tkgrid(tklabel(PlotIndFrame, text=" ")) tkgrid(RlimFrame) tkgrid(tklabel(PlotIndFrame, text=" ")) subOKCancelHelp(PlotWin, "plot.FAMD") tkgrid(PlotGrpeFrame) tkgrid(PlotVarFrame) tkgrid(PlotIndFrame, PlotWin2, sticky="ns") tkgrid(subButtonsFrame, sticky="ew", columnspan=2) } PlotFrame<-tkframe(IlluFrame) Plot.but<-tkbutton(PlotFrame, textvariable=.PlotLabel, command=OnPlot, borderwidth=3) tkgrid(Plot.but, sticky="ew") }) OnAppliquer<-function() { nom.res<-tclvalue(resu.val) if (length(which(ls(envir = .GlobalEnv, all.names = TRUE)==nom.res))>0) justDoIt(paste('remove (',nom.res,')')) ncp<-as.numeric(tclvalue(ncp.val)) Axe<-c(as.numeric(tclvalue(Axe1)), as.numeric(tclvalue(Axe2))) variables <- variables.q <- NULL if(length(as.numeric(tkcurselection(listdesc)))<1) variables <- vars.desc else variables<-vars.desc[as.numeric(tkcurselection(listdesc))+1] variables <- variables[!(variables%in%variableillu)] if(length(as.numeric(tkcurselection(listfact)))<1) variables.q <- vars.fact else variables.q<-vars.fact[as.numeric(tkcurselection(listfact))+1] variables.q <- variables.q[!(variables.q%in%variablefact)] allvariables = c(variables,variables.q,variableillu,variablefact) num.group.sup<-NULL if (length(variableillu)+length(variablefact)>0) num.group.sup <- ((length(variables)+length(variables.q)+1):length(allvariables)) if(!is.null(individuillu)) { ind.actif<-rows[-which(rows %in% individuillu)] commande.data<-paste(activeDataSet(),'.FAMD', '<-', activeDataSet(),'[c("', paste(ind.actif, collapse='", "'), '", "', paste(individuillu, collapse='", "'), '"),', sep='') } else commande.data<-paste(activeDataSet(),'.FAMD', '<-', activeDataSet(),'[,', sep='') commande.data<-paste(commande.data,' c("',paste(allvariables, collapse='", "'), '")]',sep='') justDoIt(commande.data) logger(commande.data) donnee.depart<-activeDataSet() activeDataSet(paste(activeDataSet(),'.FAMD', sep="")) commande.FAMD<-paste(nom.res, '<-FAMD(', activeDataSet(),sep='') if(!is.null(individuillu)) commande.FAMD<-paste(commande.FAMD, ', ind.sup=', nrow(get(getRcmdr(".activeDataSet")))-length(individuillu)+1, ': ', nrow(get(getRcmdr(".activeDataSet"))),sep='') commande.FAMD<-paste(commande.FAMD, ', ncp=', ncp,sep='') if (!is.null(num.group.sup)) commande.FAMD<-paste(commande.FAMD, ', sup.var=',num.group.sup[1],':',num.group.sup[length(num.group.sup)],sep='') commande.FAMD<-paste(commande.FAMD, ', graph=FALSE)',sep='') justDoIt(commande.FAMD) logger(commande.FAMD) justDoIt(paste(nom.res,'$call$call <-',deparse(commande.FAMD),sep="")) if(Rclassif==TRUE){ commande.hcpc<-paste(nom.res,'.hcpc', '<-HCPC(', nom.res, ' ,nb.clust=', Rmeth, ',consol=', Rconsolid,',min=', Rminhcpc,',max=',Rmaxhcpc,',graph=', Rgraphhcpc, ')', sep="") justDoIt(commande.hcpc) logger(commande.hcpc) if ((Axe[1]!=1)||(Axe[2]!=2)){ command.plothcpc <- paste('plot(',nom.res,'.hcpc, axes=c(', paste(Axe, collapse=", "), '),new.plot=TRUE)',sep="") justDoIt(command.plothcpc) logger(command.plothcpc) command.plothcpc2 <- paste('plot(',nom.res,'.hcpc, choice="map",axes=c(', paste(Axe, collapse=", "), '),draw.tree=FALSE, new.plot=TRUE)',sep="") justDoIt(command.plothcpc2) logger(command.plothcpc2) } if(Rreshcpc==TRUE){ doItAndPrint(paste(nom.res,'.hcpc$data.clust[,ncol(res.hcpc$data.clust),drop=F]', sep="")) doItAndPrint(paste(nom.res,'.hcpc$desc.var', sep="")) doItAndPrint(paste(nom.res,'.hcpc$desc.axes', sep="")) doItAndPrint(paste(nom.res,'.hcpc$desc.ind', sep="")) } } if (length(which(ls(envir = .GlobalEnv, all.names = TRUE)==nom.res))>0) {if (get(nom.res)$eig[1,2]==100) doItAndPrint(paste('"No graph can be plot: data are unidimensional"'))} if((Gchoix)&(length(which(ls(envir = .GlobalEnv, all.names = TRUE)==nom.res))>0)){ if (get(nom.res)$eig[1,2]!=100) { commande.plotG<-paste('plot.FAMD(', nom.res, ', axes=c(', paste(Axe, collapse=", "), '), choix="var", new.plot=TRUE, lab.var=', Glabel, sep="") commande.plotG <- paste(commande.plotG, ',col.hab = c(',sep='') auxi = 0 if (length(variables)>0){ commande.plotG <- paste(commande.plotG, 'rep("',Gcol.var,'",',length(variables),')',sep='') auxi = 1 } if (length(variables.q)>0){ if (auxi==1) commande.plotG <- paste(commande.plotG, ',',sep='') commande.plotG <- paste(commande.plotG, 'rep("',Gcol.quali,'",',length(variables.q),')',sep='') auxi=1 } if (length(variableillu)>0){ if (auxi==1) commande.plotG <- paste(commande.plotG, ',',sep='') commande.plotG <- paste(commande.plotG, 'rep("',Gcol.quanti.sup,'",',length(variableillu),')',sep='') } if (length(variablefact)>0){ if (auxi==1) commande.plotG <- paste(commande.plotG, ',',sep='') commande.plotG <- paste(commande.plotG, 'rep("',Gcol.quali.sup,'",',length(variablefact),')',sep='') } commande.plotG <- paste(commande.plotG, ')',sep='') if (is.null(GTitle)) commande.plotG <- paste(commande.plotG,')', sep="") else { if (GTitle ==" ") commande.plotG <- paste(commande.plotG,')', sep="") else commande.plotG <- paste(commande.plotG,', title="', GTitle,'")', sep="") } commande.plotG <- paste0("print(",commande.plotG,")") justDoIt(commande.plotG) logger(commande.plotG) }} if((Wchoix)&(length(which(ls(envir = .GlobalEnv, all.names = TRUE)==nom.res))>0)&(length(variables)>0)){ if (get(nom.res)$eig[1,2]!=100) { commande.plotW<-paste('plot.FAMD(', nom.res, ', axes=c(', paste(Axe, collapse=", "), '), choix="quanti", new.plot=TRUE, lab.var=', Wlabel.var, ', lim.cos2.var=', Wlim.cos, sep="") if (!is.null(Winvisible)) { commande.plotW<-paste(commande.plotW, ', invisible=c("', paste(Winvisible, collapse='", "'),'")', sep='') if(Winvisible=="actif") commande.plotW<-paste(commande.plotW, ', col.hab=c(rep("', Wcol.quanti.sup,'",length(rownames(', nom.res, '$quanti.var.sup[[1]]))),rep("', Wcol.var, '",length(rownames(', nom.res,'$quanti.var[[1]]))))', sep='') else commande.plotW<-paste(commande.plotW, ', col.hab=c(rep("', Wcol.var, '",length(rownames(', nom.res,'$quanti.var[[1]]))),rep("', Wcol.quanti.sup,'",length(rownames(', nom.res, '$quanti.var.sup[[1]]))))', sep='') } if(is.null(Winvisible)) commande.plotW<-paste(commande.plotW, ', col.hab=c(rep("', Wcol.var, '",length(rownames(', nom.res,'$quanti.var[[1]]))),rep("', Wcol.quanti.sup,'",length(rownames(', nom.res, '$quanti.var.sup[[1]]))))', sep='') if (is.null(WTitle)) commande.plotW <- paste(commande.plotW,')', sep="") else { if (WTitle ==" ") commande.plotW <- paste(commande.plotW,')', sep="") else commande.plotW <- paste(commande.plotW,', title="', WTitle,'")', sep="") } commande.plotW <- paste0("print(",commande.plotW,")") justDoIt(commande.plotW) logger(commande.plotW) }} if((Rchoix)&(length(which(ls(envir = .GlobalEnv, all.names = TRUE)==nom.res))>0)){ if (get(nom.res)$eig[1,2]!=100) { if ((Rhabillage!="none") & (Rhabillage!="ind")) { Rhabillage<-which(colnames(get(getRcmdr(".activeDataSet")))==Rhabillage) if(length(Rhabillage)==0) Rhabillage<-"none" } if (Rhabillage=="none") Rhabillage<-paste('"', Rhabillage, '"', sep="") if (Rhabillage=="ind") Rhabillage<-paste('"', Rhabillage, '"', sep="") commande.plotI<-paste('plot.FAMD(', nom.res, ', axes=c(', paste(Axe, collapse=", "), '), choix="ind", new.plot=TRUE, lab.ind=', Rlabel.indMoy, ', lab.var=', Rlabel.quali, ', habillage=', Rhabillage, sep="") if (!is.null(RXlimInd)) commande.plotI<-paste(commande.plotI, ', xlim=c(', paste(RXlimInd, collapse=", "), ')', sep='') if (!is.null(RYlimInd)) commande.plotI<-paste(commande.plotI, ', ylim=c(', paste(RYlimInd, collapse=", "), ')', sep='') if (!is.null(Rinvisible)) commande.plotI<-paste(commande.plotI, ', invisible=c("', paste(Rinvisible, collapse='", "'),'")', sep='') if (is.null(RTitle)) commande.plotI <- paste(commande.plotI,')', sep="") else { if (RTitle ==" ") commande.plotI <- paste(commande.plotI,')', sep="") else commande.plotI <- paste(commande.plotI,', title="', RTitle,'")', sep="") } } commande.plotI <- paste0("print(",commande.plotI,")") justDoIt(commande.plotI) logger(commande.plotI) } doItAndPrint(paste('summary(',nom.res,', nb.dec = 3, nbelements=10, nbind = 10, ncp = 3, file="")', sep="")) if (RFichier==""){ if(Rpropre) doItAndPrint(paste( nom.res, '$eig', sep="")) if(Rgroupe) doItAndPrint(paste( nom.res, '$group', sep="")) if(Rindividu) doItAndPrint(paste( nom.res, '$ind', sep="")) if(Rindsup) doItAndPrint(paste( nom.res, '$ind.sup', sep="")) if(Rquanti) doItAndPrint(paste( nom.res, '$quanti.var', sep="")) if(Rquantisup) doItAndPrint(paste( nom.res, '$quanti.var.sup', sep="")) if(Rquali) doItAndPrint(paste( nom.res, '$quali.var', sep="")) if(Rqualisup) doItAndPrint(paste( nom.res, '$quali.var.sup', sep="")) if(Rdescdim) doItAndPrint(paste('dimdesc(', nom.res, ', axes=1:',ncp,')', sep="")) } else { Fich = RFichier if (substr(Fich,1,1)!='"') Fich = paste('"',Fich,sep='') if (substr(Fich,nchar(Fich),nchar(Fich))!='"') Fich = paste(Fich,'"',sep='') append = FALSE if(Rpropre){ doItAndPrint(paste('write.infile(', nom.res, '$eig, file =',Fich,',append=',append,')', sep="")) append = TRUE } if(Rgroupe){ doItAndPrint(paste('write.infile(', nom.res, '$group, file =',Fich,',append=',append,')', sep="")) append = TRUE } if(Rindividu){ doItAndPrint(paste('write.infile(', nom.res, '$ind, file =',Fich,',append=',append,')', sep="")) append = TRUE } if(Rindsup){ doItAndPrint(paste('write.infile(', nom.res, '$ind.sup, file =',Fich,',append=',append,')', sep="")) append = TRUE } if(Rquanti){ doItAndPrint(paste('write.infile(', nom.res, '$quanti.var, file =',Fich,',append=',append,')', sep="")) append = TRUE } if(Rquantisup){ doItAndPrint(paste('write.infile(', nom.res, '$quanti.var.sup, file =',Fich,',append=',append,')', sep="")) append = TRUE } if(Rquali){ doItAndPrint(paste('write.infile(', nom.res, '$quali.var, file =',Fich,',append=',append,')', sep="")) append = TRUE } if(Rqualisup){ doItAndPrint(paste('write.infile(', nom.res, '$quali.var.sup, file =',Fich,',append=',append,')', sep="")) append = TRUE } if(Rdescdim) doItAndPrint(paste('write.infile(dimdesc(', nom.res, ', axes=1:',ncp,'), file =',Fich,',append=',append,')', sep="")) } activeDataSet(donnee.depart) justDoIt(paste('remove(',activeDataSet(),'.FAMD)',sep="")) logger(paste('remove(',activeDataSet(),'.FAMD)',sep="")) } Hcpc.funct<-defmacro(label, firstLabel, expr= { env<-environment() .HcpcLabel<-tclVar(paste(firstLabel, "", sep=" ")) compteur.hcpc<-0 Rclassif<-0 Rmeth <- -1 Rconsolid<-0 Rgraphhcpc<-1 Rreshcpc<-0 Rminhcpc<-3 Rmaxhcpc<-10 OnHCPC <- function() { HcpcWin<-tktoplevel() tkwm.title(HcpcWin, .Facto_gettext("HCPC options")) onOKHcpc <- function() { assign("compteur.hcpc", compteur.hcpc+1, envir=env) if(compteur.hcpc>0) tclvalue(.HcpcLabel)<-paste(label, "", sep=" ") tkconfigure(Hcpc.but, fg="blue") if(tclvalue(methValue)=="0") assign("Rmeth", 0, envir=env) else assign("Rmeth", -1, envir=env) if(tclvalue(consolidValue)=="1") assign("Rconsolid",TRUE, envir=env) else assign("Rconsolid",FALSE,envir=env) if(tclvalue(graphhcpcValue)=="1") assign("Rgraphhcpc",TRUE,envir=env) else assign("Rgraphhcpc",FALSE,envir=env) if(tclvalue(reshcpcValue)=="1") assign("Rreshcpc",TRUE,envir=env) else assign("Rreshcpc",FALSE,envir=env) assign("Rminhcpc",as.numeric(tclvalue(minhcpc)),envir=env) assign("Rmaxhcpc",as.numeric(tclvalue(maxhcpc)),envir=env) assign("Rclassif",TRUE,envir=env) tkdestroy(HcpcWin) } OKHcpc.but<-tkbutton(HcpcWin, text="OK", width=8,command=onOKHcpc) onCancelHcpc <- function() { assign("Rclassif",FALSE,envir=env) tkdestroy(HcpcWin) } CancelHcpc.but<-tkbutton(HcpcWin, text="Cancel", width=8,command=onCancelHcpc) tkgrid(tklabel(HcpcWin, text="")) tkgrid(tklabel(HcpcWin, text = .Facto_gettext("Hierarchical Clustering on Principal Components"), fg = "darkred"), column=1, columnspan = 8, sticky = "ew") meth1 <- tkradiobutton (HcpcWin) meth1.lab <- tklabel(HcpcWin,text=.Facto_gettext("interactive")) meth2 <- tkradiobutton (HcpcWin) meth2.lab <- tklabel(HcpcWin,text=.Facto_gettext("automatic")) methValue <- tclVar(paste(Rmeth)) meth.lab <- tklabel(HcpcWin,text=.Facto_gettext("Choice of the number of clusters:")) tkconfigure(meth1,variable=methValue,value="0") tkconfigure(meth2,variable=methValue,value="-1") minmaxhcpc.label<-tklabel(HcpcWin,text=.Facto_gettext("The optimal number of clusters is chosen between:")) minhcpc<-tclVar(paste(Rminhcpc)) maxhcpc<-tclVar(paste(Rmaxhcpc)) minhcpc.entry <-tkentry(HcpcWin,width="3",textvariable=minhcpc) maxhcpc.entry <-tkentry(HcpcWin,width="3",textvariable=maxhcpc) consolid.lab <- tklabel(HcpcWin,text=.Facto_gettext("Consolidate clusters")) consolid.check <- tkcheckbutton(HcpcWin) if(Rconsolid) consolidValue<-tclVar("1") else consolidValue<-tclVar("0") tkconfigure(consolid.check,variable=consolidValue) graphhcpc.lab <- tklabel(HcpcWin,text=.Facto_gettext("Print graphs")) graphhcpc.check <- tkcheckbutton(HcpcWin) if(Rgraphhcpc) graphhcpcValue <- tclVar("1") else graphhcpcValue <- tclVar("0") tkconfigure(graphhcpc.check,variable=graphhcpcValue) reshcpc.lab <- tklabel(HcpcWin,text=.Facto_gettext("Print results for clusters")) reshcpc.check <- tkcheckbutton(HcpcWin) if(Rreshcpc) reshcpcValue<-tclVar("1") else reshcpcValue <- tclVar("0") tkconfigure(reshcpc.check,variable=reshcpcValue) tkgrid(tklabel(HcpcWin,text=.Facto_gettext("Options for the clustering"), fg = "blue"), column=1, columnspan=8, sticky="we") tkgrid(tklabel(HcpcWin,text="")) tkgrid(tklabel(HcpcWin,text=sprintf(.Facto_gettext("Clustering is performed on the first %s dimensions of FAMD"),tclvalue(ncp.val))),column=1,columnspan=4,sticky="w") tkgrid(tklabel(HcpcWin,text=.Facto_gettext("(Modify in the main options to change this number)")),column=1,columnspan=4,sticky="w") tkgrid(tklabel(HcpcWin,text="")) tkgrid(meth.lab,meth1.lab,meth1) tkgrid(meth2.lab,meth2) tkgrid(tklabel(HcpcWin,text="")) tkgrid(minmaxhcpc.label,minhcpc.entry , maxhcpc.entry) tkgrid(tklabel(HcpcWin,text="")) tkgrid(consolid.lab,consolid.check) tkgrid(graphhcpc.lab,graphhcpc.check) tkgrid(reshcpc.lab,reshcpc.check) tkgrid(tklabel(HcpcWin,text="")) tkgrid(OKHcpc.but, CancelHcpc.but) tkgrid(tklabel(HcpcWin, text="")) tkgrid.configure(minmaxhcpc.label,meth.lab,consolid.lab,graphhcpc.lab,reshcpc.lab,column=1,columnspan=4,sticky="w") tkgrid.configure(minhcpc.entry,column=7,columnspan=1,sticky="e") tkgrid.configure(maxhcpc.entry,column=8,columnspan=1,sticky="w") tkgrid.configure(meth1,meth2,consolid.check,graphhcpc.check,reshcpc.check,column=8,sticky="e") tkgrid.configure(meth1.lab,column=6,columnspan=2,sticky="w") tkgrid.configure(meth2.lab,column=6,columnspan=2,sticky="w") tkgrid.configure(OKHcpc.but,column=2,columnspan=1,sticky="w") tkgrid.configure(CancelHcpc.but,column=6,columnspan=1,sticky="e") tkgrid.columnconfigure(HcpcWin,0, minsize=3) tkgrid.columnconfigure(HcpcWin,5, minsize=5) tkgrid.columnconfigure(HcpcWin,8, minsize=3) } Hcpc2Frame<-tkframe(HcpcFrame) Hcpc.but<-tkbutton(Hcpc2Frame, textvariable=.HcpcLabel, command=OnHCPC, borderwidth=3) tkgrid(Hcpc.but, sticky="ew") }) onOK<-function() { OnAppliquer() tkdestroy(top) } IlluFrame<- tkframe(top, borderwidth=2) Fillu.funct(label=.Facto_gettext("Supplementary factors"), firstLabel=.Facto_gettext("Supplementary factors")) Dillu.funct(label=.Facto_gettext("Supplementary quantitative variables"), firstLabel=.Facto_gettext("Supplementary quantitative variables")) Iillu.funct(label=.Facto_gettext("Supplementary individuals"), firstLabel=.Facto_gettext("Supplementary individuals")) PLOT.FAMD(label=.Facto_gettext("Graphical options"), firstLabel=.Facto_gettext("Graphical options")) Sortie.funct(label=.Facto_gettext("Outputs"), firstLabel=.Facto_gettext("Outputs")) tkgrid(DilluFrame, FilluFrame, IilluFrame, columnspan=7) tkgrid(tklabel(IlluFrame, text="")) tkgrid(PlotFrame, SortieFrame, columnspan=7) tkgrid.configure(DilluFrame, column=1, columnspan=1) tkgrid.configure(PlotFrame, column=2, columnspan=2,sticky="we") tkgrid.configure(SortieFrame, column=4, columnspan=2,sticky="ew") tkgrid.configure(FilluFrame, column=3, columnspan=1) tkgrid.configure(IilluFrame, column=5, columnspan=1) tkgrid.columnconfigure(IlluFrame,0, minsize=25) tkgrid.columnconfigure(IlluFrame,2, minsize=40) tkgrid.columnconfigure(IlluFrame,4, minsize=25) OptionFrame<-tkframe(top, borderwidth=2, relief="groove") resu.lab<-tklabel(OptionFrame,text=.Facto_gettext("Name of the result object: ")) resu.val<-tclVar("res") resu<-tkentry(OptionFrame,width=10,textvariable=resu.val) ncp.lab<-tklabel(OptionFrame,text=.Facto_gettext("Number of dimensions: ")) ncp.val<-tclVar("5") ncp<-tkentry(OptionFrame,width=5,textvariable=ncp.val) Axe.label<-tklabel(OptionFrame,text=.Facto_gettext("Select the dimensions for the graphs:")) Axe1<-tclVar("1") Axe2<-tclVar("2") Axe1.entry <-tkentry(OptionFrame,width="5",textvariable=Axe1) Axe2.entry <-tkentry(OptionFrame,width="5",textvariable=Axe2) tkgrid(tklabel(OptionFrame,text=.Facto_gettext("Main options"), fg = "darkred"), columnspan=8, sticky="we") tkgrid(tklabel(OptionFrame,text="")) tkgrid(ncp.lab, ncp) tkgrid(Axe.label,Axe1.entry , Axe2.entry, sticky="w") tkgrid(resu.lab, resu) tkgrid.configure(ncp.lab, resu.lab, Axe.label, column=1, columnspan=4, sticky="w") tkgrid.configure(ncp, resu, column=6, columnspan=2, sticky="e") tkgrid.configure(Axe1.entry, column=6, columnspan=1, sticky="w") tkgrid.configure(Axe2.entry, column=7, columnspan=1, sticky="e") tkgrid.columnconfigure(OptionFrame,0, minsize=25) tkgrid.columnconfigure(OptionFrame,5, minsize=40) tkgrid.columnconfigure(OptionFrame,8, minsize=25) HcpcFrame<-tkframe(top, borderwidth=2) Hcpc.funct(label=.Facto_gettext("Perform Clustering after FAMD"), firstLabel=.Facto_gettext("Perform Clustering after FAMD")) tkgrid(Hcpc2Frame, columnspan=7) tkgrid.configure(Hcpc2Frame,column=4, columnspan=1) appliquer.but<-tkbutton(top, text=.Facto_gettext("Apply"),width=12,command=OnAppliquer, borderwidth=3, fg=" OKCancelHelp(helpSubject="FAMD",reset="Reinitializ.funct") tkgrid(tklabel(top, text=.Facto_gettext("Factor Analysis of Mixed Data (FAMD)"),font=fontheading), columnspan=3) tkgrid(tklabel(top,text="")) tkgrid(listFrame, column=1, columnspan=1) tkgrid(tklabel(top,text="")) tkgrid(IlluFrame, column=1, columnspan=1) tkgrid(tklabel(top,text="")) tkgrid(OptionFrame, column=1, columnspan=1) tkgrid(tklabel(top,text="")) tkgrid(HcpcFrame, column=1, columnspan=1) tkgrid(tklabel(top,text="")) tkgrid(buttonsFrame, appliquer.but) tkgrid.configure(buttonsFrame, column=1,sticky="e") tkgrid.configure(appliquer.but, column=2,sticky="w") }
context("User Input/function output errors") test_that("Check input error messages for mpower()", { expect_error(mpower(effect_size = , study_size = 10, k = 10, i2 = .50, es_type = "d"), "Need to specify expected effect size") expect_error(mpower(effect_size = "one" , study_size = 10, k = 10, i2 = .50, es_type = "d"), "effect_size must be numeric") expect_error(mpower(effect_size = c(.5,.5), study_size = 10, k = 10, i2 = .50, es_type = "d"), "effect_size must be a single number") expect_warning(mpower(effect_size = 11, study_size = 10, k = 10, i2 = .50, es_type = "d"), "Are you sure effect size is >10?") expect_error(mpower(effect_size = .5, study_size = , k = 10, i2 = .50, es_type = "d"), "Need to specify expected sample size") expect_error(mpower(effect_size = .5, study_size = 0, k = 10, i2 = .50, es_type = "d"), "study_size must be greater than 0") expect_error(mpower(effect_size = .5, study_size = "ten", k = 10, i2 = .50, es_type = "d"), "study_size must be numeric") expect_error(mpower(effect_size = .5, study_size = c(10,10), k = 10, i2 = .50, es_type = "d"), "study_size must be a single number") expect_error(mpower(effect_size = .5, study_size = 10, k = , i2 = .50, es_type = "d"), "Need to specify expected number of studies") expect_error(mpower(effect_size = .5, study_size = 10, k = "ten", i2 = .50, es_type = "d"), "k must be numeric") expect_error(mpower(effect_size = .5, study_size = 10, k = c(10,10), i2 = .50, es_type = "d"), "k must be a single number") expect_error(mpower(effect_size = .5, study_size = 10, k = 1, i2 = .50, es_type = "d"), "k must be greater than 1") expect_error(mpower(effect_size = .5, study_size = 10, k = 10, i2 = .50, es_type = ), "Need to specify effect size as 'd', 'r', or 'or'") expect_error(mpower(effect_size = .5, study_size = 10, k = 10, i2 = .50, es_type = 1), "Need to specify effect size as 'd', 'r', or 'or'") expect_error(mpower(effect_size = .5, study_size = 10, k = 10, i2 = .50, es_type = "d", test_type = 1), "Need to specify two-tailed or one-tailed") }) test_that("check that output is an 'mpower' class", { expect_match(class(mpower(effect_size = .5, study_size = 10, k = 10, i2 = .50, es_type = "d")), "mpower") }) test_that("Check input error messages for subgroup_power()", { expect_error(subgroup_power(n_groups = 2, effect_sizes = .5, study_size = 20, k = 20, i2 = .5, es_type = "d"), "The number of of effect sizes should match the number of groups") expect_error(subgroup_power(n_groups = 2, effect_sizes = c(".1", ".5"), study_size = 20, k = 20, i2 = .5, es_type = "d"), "Effect sizes must be numeric") expect_error(subgroup_power(n_groups = 2, effect_sizes = c(.1,.5), study_size = c(20,20), k = 20, i2 = .5, es_type = "d"), "study_size must be a single number") expect_error(subgroup_power(n_groups = 2, effect_sizes = c(.1,.5), study_size = "twenty", k = 20, i2 = .5, es_type = "d"), "study_size must be numeric") expect_error(subgroup_power(n_groups = 2, effect_sizes = c(.1,.5), study_size = 20, k = 20, i2 = .5, es_type = "or"), "For Odds Ratio, only enter the 2x2 contingency table. Remove effect_size argument") expect_error(subgroup_power(n_groups = 2, study_size = 20, k = 20, i2 = .5, es_type = "or", con_table = c(5,5,5,5)), "con_table should be input as a list with each element reflect the group 2x2 tables") expect_error(subgroup_power(n_groups = 2, study_size = 20, k = 20, i2 = .5, es_type = "or", con_table = list(g = c(5,5,5,5))), "Only 1 group 2x2 table is specified") expect_error(subgroup_power(n_groups = 2, con_table = list(g1 = c(6,5,4,5), g2 = c("hello")), study_size = 20, k = 20, i2 = .5, es_type = "or"),"Each element of con_table should be numeric") }) test_that("check that output is an 'subgroup_power' class", { expect_match(class(subgroup_power(n_groups = 2, con_table = list(g1 = c(6,5,4,5), g2 = c(8,5,2,5)), study_size = 40, k = 20, i2 = .5, es_type = "or")), "subgroup_power") })
NULL predict.standardized <- function(object, newdata = NULL, response = FALSE, fixed = TRUE, random = TRUE, ...) { stopifnot(is.standardized(object), is.data.frame(newdata)) check_dots_predict.standardized(...) p <- object$pred if (fixed && !random) { p <- p$fixed } else if (!fixed && random) { p <- p$random } else if (fixed && random) { p <- p$all } else { stop("'fixed' and 'random' cannot both be FALSE") } if (!response) { p <- p[-2] } if (length(p) < 2) { stop("No variables when response = ", response, ", fixed = ", fixed, ", and random = ", random, ".") } fr <- setNames(data.frame(matrix(nrow = nrow(newdata), ncol = length(p) - 1)), names(p)[-1]) fr[names(p)[-1]] <- eval(p, envir = newdata) fr <- strip_attr(fr) return(fr) } is.standardized <- function(object) { return(inherits(object, "standardized")) } print.standardized <- function(x, ...) { sc <- round(x$scale, 3) cat("\nCall:\n") cl <- x$call f <- get_family(x$family) cl["family"] <- NULL print(cl) if (is.character(f)) { cat("\nFamily:", f, "\n\n") } else { print(f) } cat("Standardized Formula:\n") f <- x$formula attr(f, "standardized.scale") <- NULL print(f, showEnv = FALSE) cat("\nVariables:\n") print(x$variables, row.names = FALSE, right = FALSE) o <- any(x$variables$Class == "offset") | !is.null(x$offset) if (is.linear(f <- x$family)) { if (x$variables$Class[1] %in% c("response.scaledby", "response.scaledby.poly")) { cat("\nResponse has mean 0 and standard deviation 1 ", "within each factor level.\n", sep = "") if (o) { cat("Offsets are divided by the standard deviation of the raw response", "within each factor level.\n") } } else { cat("\nResponse has mean 0 and standard deviation 1.\n") if (o) { cat("Offsets are divided by the standard deviation of the raw response.\n") } } } else { if (!is.character(f)) f <- paste0(f$family, "(", f$link, ")") cat("\nResponse not altered because family = ", f, "\n", sep = "") if (o) { cat("Offsets are unaltered for the same reason.\n") } } cat( "\nContinuous variables have mean 0 and standard deviation ", sc, "\n", " (within-factor-level if scale_by was used)\n", "Unordered factors have sum contrasts with deviation ", sc, "\n", "Ordered factors have orthogonal polynomial contrasts whose\n", " columns have standard deviation ", sc, "\n", "Grouping factors are coded as unordered factors with default contrasts\n", "\n", sep = "") }
plotFit = function(concData, id, Time, conc, mol="", adm="Extravascular", ID="", Mol="") { if (mol == "") { x = concData[concData[,id] == ID, Time] y = concData[concData[,id] == ID, conc] } else { x = concData[concData[,id] == ID & concData[,mol] == Mol, Time] y = concData[concData[,id] == ID & concData[,mol] == Mol, conc] } finalMat = BestSlope(x, y, adm=adm) y1 = ifelse(y==0, 0.1, y) plot(x, log(y), yaxt = "n", ylim=c(min(log(y1)), finalMat["b0"]), xlab="Time", ylab="Concentration", main=paste("Best Fit ID:", ID)) yticks = seq(round(min(log(y1))), ceiling(max(log(y1)))) ylabels = sapply(yticks, function(i) as.expression(bquote(e^ .(i)))) axis(2, at=exp(yticks), labels=ylabels) abline(a=finalMat["b0"],b=-finalMat["LAMZ"], untf=TRUE, col="blue") return(finalMat) }
print.betaor <- function(x, ...){ cat("Call:\n") print(x$call) cat("\nOdds Ratio:\n") printCoefmat(x$oddsratio,P.values=T,has.Pvalue=T) }
tar_branch_names <- function( name, index, store = targets::tar_config_get("store") ) { name <- tar_deparse_language(substitute(name)) tar_assert_chr(name) tar_branch_names_raw(name = name, index = index, store = store) }
library(tidyverse) library(repurrrsive) film_number_lookup <- map_chr(sw_films, "url") %>% map(~ stringr::str_split_fixed(.x, "/", 7)[, 6]) %>% as.numeric() %>% set_names(map_chr(sw_films, "url")) people_tbl <- tibble( name = sw_people %>% map_chr("name"), films = sw_people %>% map("films"), height = sw_people %>% map_chr("height") %>% readr::parse_number(na = "unknown"), species = sw_people %>% map_chr("species", .null = NA_character_) ) people_tbl$films people_tbl <- people_tbl %>% mutate( film_numbers = map(films, ~ film_number_lookup[.x]), n_films = map_int(films, length) ) people_tbl %>% select(name, film_numbers, n_films) people_tbl <- people_tbl %>% mutate(films_squashed = map_chr(film_numbers, paste, collapse = ", ")) people_tbl %>% select(name, n_films, films_squashed)
apportion_scores_comp <- function(obj){ if(is.null(obj$comp_loadings)){ return('The input needs to be the object returned by the function comp_tsout_ens!') } nsp <- obj$comp_loadings outmat4D <- obj$outmat4D decomp_wts <- obj$decomp_wts out_wts <- obj$wts outmat3D <- out_wts[1]*outmat4D[ ,1, , ] + out_wts[2]*outmat4D[ ,2, , ] + out_wts[3]*outmat4D[ ,3, , ] + out_wts[4]*outmat4D[ ,4, , ] scores_dobin <- outmat3D[ , ,1] %*% diag(decomp_wts[ ,1]) scores_pca <- outmat3D[ , ,2] %*% diag(decomp_wts[ ,2]) scores_ics <- outmat3D[ , ,3] %*% diag(decomp_wts[ ,3]) scores_ica <- outmat3D[ , ,4] %*% diag(decomp_wts[ ,4]) if(length(obj$dobin_loadings)==1){ a_dobin <- 0 }else{ a_dobin <- nsp%*% obj$dobin_loadings%*% t(scores_dobin) } if(length(obj$pca_loadings)==1){ a_pca <- 0 }else{ a_pca <- nsp%*% obj$pca_loadings%*% t(scores_pca) } if(length(obj$ics_loadings)==1){ a_ics <- 0 }else{ a_ics <- nsp%*% obj$ics_loadings%*% t(scores_ics) } if(length(obj$ica_loadings)==1){ a_ica <- 0 }else{ a_ica <- nsp%*% obj$ica_loadings%*% t(scores_ica) } a <- abs(a_dobin) + abs(a_pca) + abs(a_ics) + abs(a_ica) obj$all <- as.data.frame(obj$all) inds <- obj$all$Indices tscore <- obj$all$Total_Score a_ori <- t(a[ ,inds]) a_ori <- as.data.frame(a_ori) rownames(a_ori) <- paste(inds) indsout <- obj$outliers$Indices if(length(indsout) > 0){ a_out <- a[ ,indsout] }else{ a_out <- NA } a_out <- as.data.frame(a_out) colnames(a_out) <- paste(indsout) out <- list() out$scores_out<- a_out out$scores_all <- t(a_ori) return(out) }
"BackwardStepOne" <- function(y, lastkgroup = floor(0.01*n), kmin = 5) { n <- length(y) m <- y z <- rep(1, n) rss <- z[1:(n-1)] * z[2:n] / (z[1:(n-1)] + z[2:n]) * (m[1:(n-1)] - m[2:n])^2 l <- n value <- rep(0, n) index <- rep(0, n) ngroup <- lastkgroup sigma <- estimateSigma(y, h = 10) cutoff <- 1.0e+12 temp <- .C("backward", as.double(m), as.integer(z), as.double(rss), as.integer(n), as.integer(l), as.double(value), as.integer(index), as.double(sigma), as.double(cutoff), as.integer(ngroup), as.integer(kmin)) l <- temp[[5]] m <- temp[[1]][1:l] z <- temp[[2]][1:l] rss <- c(temp[[3]][1:(l-1)], NA) index <- c(1, cumsum(z)[-l]+1) obj <- cbind(index, m, z, rss) colnames(obj) <- c("index", "mean", "size", "rss") return(obj) }
setGeneric("stretchPlot", function(x, type = "linear", n, ...) { standardGeneric("stretchPlot") }) setMethod("stretchPlot", signature(x = "RasterLayer"), function(x, type = "linear", n, ...) { xx <- pretty(values(x), 2) p <- length(xx) if(type == "hist.equal") { y <- .stretch(x, type = "hist.equal") plot(y[[1]], breaks = .quantile_breaks(y[[1]]), axis.args = list(at = y[[2]][-p], labels = xx[-p]), ...) } if(type == "linear") { y <- .stretch(x, type = "linear") plot(y[[1]], axis.args = list(at = y[[2]], labels = xx), ...) } if(type == "sd") { y <- .stretch(x, type = "sd", n = n) f <- duplicated(y[[2]]) plot(y[[1]], axis.args = list(at = y[[2]][!f], labels = xx[!f]), ...) } return(NULL) } ) .stretch <- function(x, type = "hist.equal", n) { if (type == "hist.equal") { ecdfun <- stats::ecdf(getValues(x)) y <- calc(x, fun = function(x) round(ecdfun(x)*255, 0)) v <- pretty(values(x), 2) vv <- round(ecdfun(v)*255, 0) return(list(y, vv)) } else if (type == "sd") { if (missing(n)) stop("number of standard deviations not specified") x.sd <- cellStats(x, sd) x.mean <- cellStats(x, mean) x.max <- x.mean + x.sd*n x.min <- x.mean - x.sd*n sdfun <- function(y) { y[y < 0] <- x.min y[y > x.max] <- x.max tt <- (y - x.min) / (x.max - x.min) return(tt*255) } y <- calc(x, fun = function(x) sdfun(x)) v <- pretty(values(x), 2) vv <- sdfun(v) return(list(y, vv)) } else if (type == "linear") { y <- x vv <- pretty(values(x), 2) return(list(y, vv)) } } .quantile_breaks <- function(ras){ qts <- quantile(ras) seq1 <- seq(qts[1], qts[2], length.out = 65) seq2 <- seq(qts[2], qts[3], length.out = 65) seq3 <- seq(qts[3], qts[4], length.out = 65) seq4 <- seq(qts[4], qts[5], length.out = 64) brks <- c(seq1, seq2[-1], seq3[-1], seq4[-1]) brks }
GParetoMultipleMEFPlot <- function(Ra, mu, beta, zeta1, zeta2) { x <- as.vector(Ra) x <- sort(x) u <- x n <- length(u) mef <- double(n - 1) for (i in 1:(n - 1)) { x <- x[which(x > u[i])] mef[i] <- mean(x) - u[i] } u <- t(u) u <- u[u!=max(u)] gpmef1 <- (1 + zeta1 * (u - mu) / beta)/(1 - zeta1); gpmef2 <- (1 + zeta2 * (u - mu) / beta)/(1 - zeta2); xlims <- c(min(u),max(u)) ylims <- c(min(mef, gpmef1, gpmef2), max(mef, gpmef1, gpmef2)) plot(u , mef, xlims, ylims, type = "l", xlab = "Threshold (u)", col = 5, ylab = "e(u)") par(new = TRUE) plot(u , gpmef1, xlims, ylims, type = "l", xlab = "Threshold (u)", col = 4, ylab = "e(u)") par(new = TRUE) plot(u , gpmef2, xlims, ylims, type = "l", xlab = "Threshold (u)", col = 3, ylab = "e(u)") title("Emperical and Two Generalised Pareto MEFs") legend("topright", legend = c("Emperical MEF", "Generalized Pareto MEF1", "Generalized Pareto MEF1"), text.col = c(5,4,3)) }
get_github_hash <- function(repo) { if (!grepl("version", system("git --version", intern = TRUE))) { msg <- paste("git must be installed and located in the system path", "for this function to work") stop(msg) } tmp <- system(paste("git ls-remote -h", repo), intern = TRUE) strsplit(tmp, "\\\\|[^[:print:]]")[[1]][1] }
dashboard <- function(limit=20,offset=0,type=NA,since_id=0,reblog_info=FALSE,notes_info=FALSE, token=NA,consumer_key=NA,consumer_secret=NA){ if(!is.numeric(limit) || (limit<1 || limit>20) ) stop("limit must be a numeric type beetwen 1 and 20 (inclusive)") if(!is.numeric(offset)) stop("offset must be a numeric type") if(!is.numeric(since_id)) stop("since_id must be a number") if(!(is.logical(reblog_info))) stop("reblog_info must be a boolean") if(!(is.logical(notes_info))) stop("reblog_info must be a boolean") if(class(token)[1]!="Token1.0") stop("token must be a Token1.0 type") if(!is.character(consumer_key)) stop("consumer_key must be a string") if(!is.character(consumer_secret)) stop("consumer_secret must be a string") if(!is.na(type)){ format_type<-c("HTML","text","raw") if(!(type %in% format_type)) stop("Avaliable values for filter are: HTML, text, raw") } url<-"https://api.tumblr.com/v2/user/dashboard" connection<-"GET" Params<-list(limit=limit,offset=offset,type=type,since_id=since_id, reblog_info=reblog_info,notes_info=notes_info) len<-length(Params) s<-NULL for(i in 1:len){ if(!is.na(Params[[i]][1])) s<-c(s,i) } bodyParams<-Params[s] res<-toJSON(http.connection(url,token,bodyParams,consumer_key,consumer_secret,connection)) return(res) }
library(idendr0) data(iris) hc <- hclust(dist(iris[, 1:4])) clusters <- idendro(hc, iris) idendro(hc, iris, clusters=clusters)
epa_loadAnnual <- function( year = NULL, parameterCode = NULL, baseUrl = 'https://haze.airfire.org/monitoring', dataDir = NULL ) { validParameterCodes <- c("88101", "88502") if ( is.null(parameterCode) ) { stop("Required parameter 'parameterCode' is missing") } else { parameterCode <- as.character(parameterCode) if ( !parameterCode %in% validParameterCodes ) { stop(paste0("PWFSL has not yet processed EPA data for parameterCode '", parameterCode, "'")) } } if ( is.null(year) ) { stop(paste0("Required parameter 'year' is missing")) } year <- as.numeric(year) lastYear <- lubridate::now(tzone = "UTC") %>% lubridate::year() - 1 if ( parameterCode == "88101" ) { parameter <- "PM2.5" if ( ! year %in% 2008:lastYear) { stop(sprintf("No EPA data available for parameter code %s in year %i", parameterCode, year)) } } else if ( parameterCode == "88502" ) { parameter <- "PM2.5" if ( ! year %in% 1998:lastYear) { stop(sprintf("No EPA data available for parameter code %s in year %i", parameterCode, year)) } } baseUrl <- paste0(baseUrl, '/EPA/RData/', year) filename <- paste0("epa_", parameter, "_", parameterCode, '_', year, ".RData") ws_monitor <- MazamaCoreUtils::loadDataFile(filename, baseUrl, dataDir) return(ws_monitor) }
d_inventory <- function(fsq, sta_sen=NA, form.out=NA){ if (!file.exists(fsq)) return(warning("\nThis data base doesn't exist, Verify!\n")) if(!(form.out %in% c(NA, "xlsx", "csv,", "csv;"))) form.out <- NA conn <- RSQLite::dbConnect(RSQLite::SQLite(),fsq) ltab <- RSQLite::dbListTables(conn) if(!("ST" %in% ltab)){ RSQLite::dbDisconnect(conn) return(warning("\nThis data base doesn't have station table.\n")) } sel <- paste ("SELECT * FROM ST") lsta <- RSQLite::dbGetQuery(conn, sel) nsta <- nrow(lsta) if (nsta == 0){ RSQLite::dbDisconnect(conn) return(warning("\nNo station in the data base\n")) } stac <- nom_stac <-senc <- descric <-tablec <- nbrc <- d_endc <- d_startc <- NULL nosensor <- nostation <- NULL Id_station <- Sensor <- NULL Altitude <- Id_Station <- Latitude <- Longitude <- Nom <- Pays <- Station_type <- NULL Superficie_bv <- Type_Station <- NULL x1 <- dplyr::select(lsta, Id_station = Id_Station, Station_type = Type_Station, Station_name = Nom, Country = Pays, Latitude, Longitude, Altitude, Basin_areas = Superficie_bv) x1 <- dplyr::arrange(x1, Station_type, Id_station) if (is.na(sta_sen)) { for(i in 1: nsta){ sta <- lsta$Id_Station[i] nom_sta <- lsta$Nom[i] sta1 <- paste0("'",sta, "'") sel <- paste ("SELECT * FROM SS WHERE Id_Station =", sta1) lsen <- RSQLite::dbGetQuery(conn, sel) nsen <- nrow(lsen) if (nsen == 0) { message("The station ", sta, " has no sensor") } else for(j in 1: nsen) { sen <- lsen$Capteur[j] sen1 <- paste0("'",sen, "'") sel <- paste ("SELECT * FROM SS WHERE Id_Station =", sta1, "AND Capteur =", sen1) x <- RSQLite::dbGetQuery(conn, sel) descri <- x$Description tablex <- x$Tabl sel <- paste ("SELECT * FROM", tablex, "WHERE Id_Station =", paste0("'",sta, "'"), "AND Capteur =", paste0("'",sen, "'")) x <- RSQLite::dbGetQuery(conn, sel) nbr <- nrow(x) if (nbr > 0) { xd <- as.POSIXct(x$Date, origin = "1970-01-01", tz = "UTC") d_start <- min(xd) d_end <- max(xd) } else d_start <- d_end <- NA stac <- c(stac, sta) nom_stac <- c(nom_stac, nom_sta) senc <- c(senc, sen) descric <- c(descric, descri) tablec <- c(tablec, tablex) nbrc <- c(nbrc, nbr) d_endc <- c(d_endc, d_end) d_startc <- c(d_startc, d_start) } } } else { if(sta_sen %in% lsta$Id_Station) { k <- 0 for (j in 1:length(lsta$Id_Station)) if(sta_sen == lsta$Id_Station[j]) k <- j sta <- lsta$Id_Station[k] nom_sta <- lsta$Nom[k] sta1 <- paste0("'",sta, "'") sel <- paste ("SELECT * FROM SS WHERE Id_Station =", sta1) lsen <- RSQLite::dbGetQuery(conn, sel) nsen <- nrow(lsen) if (nsen == 0) nosensor <- sta else for(j in 1: nsen) { sen <- lsen$Capteur[j] sen1 <- paste0("'",sen, "'") sel <- paste ("SELECT * FROM SS WHERE Id_Station =", sta1, "AND Capteur =", sen1) x <- RSQLite::dbGetQuery(conn, sel) descri <- x$Description tablex <- x$Tabl sel <- paste ("SELECT * FROM", tablex, "WHERE Id_Station =", paste0("'",sta, "'"), "AND Capteur =", paste0("'",sen, "'")) x <- RSQLite::dbGetQuery(conn, sel) nbr <- nrow(x) if (nbr > 0) { xd <- as.POSIXct(x$Date, origin = "1970-01-01", tz = "UTC") d_start <- min(xd) d_end <- max(xd) } else d_start <- d_end <- NA stac <- c(stac, sta) nom_stac <- c(nom_stac, nom_sta) senc <- c(senc, sen) descric <- c(descric, descri) tablec <- c(tablec, tablex) nbrc <- c(nbrc, nbr) d_endc <- c(d_endc, d_end) d_startc <- c(d_startc, d_start) } } else nostation <- sta_sen } if (!is.null(nostation)) x2 <- tibble (station = nostation, comment = " is not in the data base") else { if (!is.null(nosensor)) x2 <- tibble (station = nosensor, comment = " has no sensor") else { x2 <- tibble::tibble(Id_station = stac, Station_name = nom_stac, Sensor = senc, Description = descric, Table = tablec, Nb_Rec = nbrc, Date_start = as_datetime(d_startc), Date_end = as_datetime(d_endc)) x2 <- dplyr::arrange(x2, Id_station, Sensor) } } RSQLite::dbDisconnect(conn) if(is.na(form.out)== TRUE) { a <- list(x1, x2) return(a) } else { nfse <- tools::file_path_sans_ext(fsq) fileo1 <- paste0(nfse, "_inv-sta") fileo2 <- paste0(nfse, "_inv-sen") if(form.out== "csv,") { fileo1 <- paste0(fileo1,".csv") fileo2 <- paste0(fileo2,".csv") write.csv (x1,file=fileo1, row.names=FALSE) write.csv (x2,file=fileo2, row.names=FALSE) return(message("\nThe files ",fileo1," and ", fileo2," are written.\n")) } if(form.out== "csv;"){ fileo1 <- paste0(fileo1,".csv") fileo2 <- paste0(fileo2,".csv") write.csv2 (x1,file=fileo1, row.names=FALSE) write.csv2 (x2,file=fileo2, row.names=FALSE) return(message("\nThe files ",fileo1," and ", fileo2," are written.\n")) } if(form.out== "xlsx"){ fileo <- paste0(paste0(nfse, "_inv"),".xlsx") xx <- list(x1,x2) WriteXLS::WriteXLS (xx, ExcelFileName=fileo,SheetNames=c("Stations","Sensors"), col.names=TRUE, row.names=FALSE, na=" return(message("\nThe file ",fileo," is written.\n")) } } }
tindex <- function(x) { if (!is_term(x) && !is_term_rcrd(x)) { lifecycle::deprecate_soft( "0.2.1", "term::tindex(x = 'must be a term or term_rcrd object')" ) x <- as_term(x) } tindex <- field(as_term_rcrd(x), "dim") names(tindex) <- as.character(as_term(x)) tindex }
optim.gene.norm <- function(y,status,weight,param,x=NULL,var.list=NULL) { mu <- sigma <- list() mu.mat.old <- mu.mat <- matrix(NA,nrow=ncol(weight),ncol=ncol(y)) sigma.array.old <- sigma.array <- array(NA,c(ncol(weight),ncol(y),ncol(y))) for(k in 1:ncol(weight)) { mu.mat.old[k,] <- param$mu[[k]] sigma.array.old[k,,] <- param$sigma[[k]] } for(j in 1:ncol(y)) { indivs <- which(is.finite(y[,j])) weight.aff <- matrix(weight[status==2,],nrow=sum(status==2),ncol=ncol(weight)) weight.miss <- matrix(weight[status==0,],nrow=sum(status==0),ncol=ncol(weight)) weight.aff.j <- matrix(weight.aff[indivs,],nrow=length(indivs),ncol=ncol(weight)) mu.mat[,j] <- t(weight.aff.j)%*%y[indivs,j] mu.mat[,j] <- mu.mat[,j]+apply(weight.miss,2,sum)*mu.mat.old[,j] mu.mat[,j] <- mu.mat[,j]/(apply(weight.aff.j,2,sum)+apply(weight.miss,2,sum)) } for(j1 in 1:ncol(y)) for(j2 in 1:ncol(y)) { indivs <- intersect(which(is.finite(y[,j1])),which(is.finite(y[,j2]))) weight.aff <- matrix(weight[status==2,],nrow=sum(status==2),ncol=ncol(weight)) weight.miss <- matrix(weight[status==0,],nrow=sum(status==0),ncol=ncol(weight)) weight.aff.j1j2 <- matrix(weight.aff[indivs,],nrow=length(indivs),ncol=ncol(weight)) sigma.array[,j1,j2] <- diag(t(weight.aff.j1j2)%*%(outer(y[indivs,j1],mu.mat[,j1],"-")*outer(y[indivs,j2],mu.mat[,j2],"-"))) sigma.array[,j1,j2] <- sigma.array[,j1,j2]+apply(weight.miss,2,sum)*(sigma.array.old[,j1,j2]+(mu.mat.old[,j1]-mu.mat[,j1])*(mu.mat.old[,j2]-mu.mat[,j2])) sigma.array[,j1,j2] <- sigma.array[,j1,j2]/(apply(weight.aff.j1j2,2,sum)+apply(weight.miss,2,sum)) } for(k in 1:ncol(weight)) { mu[[k]] <- mu.mat[k,] sigma[[k]] <- matrix(sigma.array[k,,],nrow=ncol(y),ncol=ncol(y)) } param <- list("mu"=mu,"sigma"=sigma) param }
mdes.bcra3r2 <- function(power=.80, alpha=.05, two.tailed=TRUE, rho2, rho3, esv3=NULL, omega3=esv3/rho3, p=.50, g3=0, r21=0, r22=0, r2t3=0, n, J, K){ user.parms <- as.list(match.call()) .error.handler(user.parms) df <- K - g3 - 1 SSE <- sqrt(rho3*omega3*(1-r2t3)/K + rho2*(1-r22)/(p*(1-p)*J*K) + (1-rho3-rho2)*(1-r21)/(p*(1-p)*J*K*n)) mdes <- .mdes.fun(power = power, alpha = alpha, sse = SSE, df = df, two.tailed = two.tailed) .summ.mdes(effect = "main", power = power, alpha = alpha, sse = SSE, df = df, two.tailed = two.tailed, mdes = mdes) mdes.out <- list(fun = "mdes.bcra3r2", parms = list(power=power, alpha=alpha, two.tailed=two.tailed, rho2=rho2, rho3=rho3, esv3=esv3, omega3=omega3, p=p, r21=r21, r22=r22, r2t3=r2t3, g3=g3, n=n, J=J, K=K), df=df, ncp = mdes[1]/SSE, mdes = mdes) class(mdes.out) <- c("main", "mdes") return(invisible(mdes.out)) } power.bcra3r2 <- function(es=.25, alpha=.05, two.tailed=TRUE, rho2, rho3, esv3=NULL, omega3=esv3/rho3, p=.50, g3=0, r21=0, r22=0, r2t3=0, n, J, K){ user.parms <- as.list(match.call()) .error.handler(user.parms) df <- K - g3 - 1 SSE <- sqrt(rho3*omega3*(1-r2t3)/K + rho2*(1-r22)/(p*(1-p)*J*K) + (1-rho3-rho2)*(1-r21)/(p*(1-p)*J*K*n)) power <- .power.fun(es = es, alpha = alpha, sse = SSE, df = df, two.tailed = two.tailed) .summ.power(power = power, alpha = alpha, sse = SSE, df = df, two.tailed = two.tailed, es = es) power.out <- list(fun = "power.bcra3r2", parms = list(es=es, alpha=alpha, two.tailed=two.tailed, rho2=rho2, rho3=rho3, esv3=esv3, omega3=omega3, p=p, r21=r21, r22=r22, r2t3=r2t3, g3=g3, df=df, n=n, J=J, K=K), df=df, ncp = es/SSE, power = power) class(power.out) <- c("main", "power") return(invisible(power.out)) } mrss.bcra3r2 <- function(es=.25, power=.80, alpha=.05, two.tailed=TRUE, n, J, K0=10, tol=.10, rho2, rho3, esv3=NULL, omega3=esv3/rho3, p=.50, g3=0, r21=0, r22=0, r2t3=0){ user.parms <- as.list(match.call()) .error.handler(user.parms) i <- 0 conv <- FALSE while(i<=100 & conv==FALSE){ df = K0-g3-1 if(df<= 0 | is.infinite(df)){break} T1 <- ifelse(two.tailed==TRUE,abs(qt(alpha/2,df)),abs(qt(alpha,df))) T2 = abs(qt(power,df)) M <- ifelse(power>=.5,T1+T2,T1-T2) K1 <- (M/es)^2 * (rho3*omega3*(1-r2t3) + rho2*(1-r22)/(p*(1-p)*J) + (1-rho3-rho2)*(1-r21)/(p*(1-p)*J*n)) K0 <- (K1+K0)/2 i <- i+1 } K <- ifelse(df>0,round(K0),NA) mrss.out <- list(fun = "mrss.bcra3r2", parms = list(es=es, power=power, alpha=alpha, two.tailed=two.tailed, n=n, J=J, K0=K0, tol=tol, rho2=rho2, rho3=rho3, esv3=esv3, omega3=omega3, p=p, r21=r21, r22=r22, r2t3=r2t3, g3=g3), df=df, ncp = M, K = K) class(mrss.out) <- c("main", "mrss") cat("K =", K, "\n") return(invisible(mrss.out)) } mdes.bcra3r2_pn <- function(power=.80, alpha=.05, two.tailed=TRUE, df=NULL, rho3_trt=.10, omega3=.50, rho2_trt=.20, rho_ic=0, p=.50, r21=0, g3=0, n, J, K, ic_size=1){ user.parms <- as.list(match.call()) .error.handler(user.parms) if(ic_size == 1 & rho_ic != 0) { rho_ic <- 0 warning("Forcing 'rho_ic = 0'", call. = FALSE) } else if(ic_size > 1 & rho_ic == 0) { warning("'rho_ic = 0'?", call. = FALSE) } if(is.null(df)) { df <- K - g3 - 1 } deff_rand_ic <- 1 + ((rho3_trt * omega3 * J * n * p * (1 - p) - rho3_trt) + rho2_trt * (n - 1) + rho_ic * (1 - p) * (ic_size - 1)) / (1 - p * rho_ic) SSE <- sqrt(((1 - r21) / (K * J * n * p * (1 - p))) * ((1 - p * rho_ic) / (1 - rho_ic)) * deff_rand_ic) mdes <- .mdes.fun(power = power, alpha = alpha, sse = SSE, df = df, two.tailed = two.tailed) .summ.mdes(effect = "main", power = power, alpha = alpha, sse = SSE, df = round(df,3), two.tailed = two.tailed, mdes = mdes) mdes.out <- list(fun = "mdes.bcra3r2_pn", parms = list(power=power, alpha=alpha, two.tailed=two.tailed, rho3_trt=rho3_trt, omega3=omega3, rho2_trt=rho2_trt, rho_ic = rho_ic, r21=r21, p=p, n=n, J=J, K=K, ic_size=ic_size), df = df, ncp = mdes[1]/SSE, mdes = mdes) class(mdes.out) <- c("main", "mdes") return(invisible(mdes.out)) } power.bcra3r2_pn <- function(es=.25,alpha=.05, two.tailed=TRUE, df=NULL, rho3_trt=.10, omega3=.50, rho2_trt=.20, rho_ic=0, p=.50, r21=0, g3=0, n, J, K, ic_size=1){ user.parms <- as.list(match.call()) .error.handler(user.parms) if(ic_size == 1 & rho_ic != 0) { rho_ic <- 0 warning("Forcing 'rho_ic = 0'", call. = FALSE) } else if(ic_size > 1 & rho_ic == 0) { warning("'rho_ic = 0'?", call. = FALSE) } if(is.null(df)) { df <- K - g3 - 1 } deff_rand_ic <- 1 + ((rho3_trt * omega3 * J * n * p * (1 - p) - rho3_trt) + rho2_trt * (n - 1) + rho_ic * (1 - p) * (ic_size - 1)) / (1 - p * rho_ic) SSE <- sqrt(((1 - r21) / (K * J * n * p * (1 - p))) * ((1 - p * rho_ic) / (1 - rho_ic)) * deff_rand_ic) power <- .power.fun(es = es, alpha = alpha, sse = SSE, df = df, two.tailed = two.tailed) .summ.power(power = power, alpha = alpha, sse = SSE, df = round(df,3), two.tailed = two.tailed, es = es) power.out <- list(fun = "power.bcra3r2_pn", parms = list(es=es, alpha=alpha, two.tailed=two.tailed, rho3_trt=rho3_trt, omega3=omega3, rho2_trt=rho2_trt, rho_ic=rho_ic, r21=r21, p=p, n=n, J=J, K=K, ic_size=ic_size), df = df, ncp = es/SSE, power = power) class(power.out) <- c("main", "power") return(invisible(power.out)) } mrss.bcra3r2_pn <- function(es=.25, power=.80, alpha=.05, two.tailed=TRUE, z.test=FALSE, rho3_trt=.10, omega3 = .50, rho2_trt=.20, rho_ic=0, p=.50, r21=0, g3=0, n, J, ic_size=1, K0=10, tol=.10){ user.parms <- as.list(match.call()) .error.handler(user.parms) if(ic_size == 1 & rho_ic != 0) { rho_ic <- 0 warning("Forcing 'rho_ic = 0'", call. = FALSE) } else if(ic_size > 1 & rho_ic == 0) { warning("'rho_ic = 0'?", call. = FALSE) } i <- 0 conv <- FALSE while(i<=100 & conv==FALSE){ df <- K0 - g3 - 1 if(df <= 0) stop("Increase 'K0'", call. = FALSE) if(df <= 0 | is.infinite(df)){break} if(z.test) df <- Inf T1 <- ifelse(two.tailed==TRUE,abs(qt(alpha/2,df)),abs(qt(alpha,df))) T2 <- abs(qt(power,df)) M <- ifelse(power>=.5,T1+T2,T1-T2) deff_rand_ic <- 1 + ((rho3_trt * omega3 * J * n * p * (1 - p) - rho3_trt) + rho2_trt * (n - 1) + rho_ic * (1 - p) * (ic_size - 1)) / (1 - p * rho_ic) VAR <- ((1 - r21) / (J * n * p * (1 - p))) * ((1 - p * rho_ic) / (1 - rho_ic)) * deff_rand_ic K1 <- (M/es)^2 * VAR if(abs(K1-K0)<tol){conv <- TRUE} K0 <- (K1+K0)/2 i <- i+1 } K <- round(ifelse(df>0,round(K0),NA)) K.out <- list(fun = "mrss.bcra3r2_pn", parms = list(es=es, power=power, alpha=alpha, two.tailed=two.tailed, rho3_trt=rho3_trt, omega3=omega3, rho2_trt=rho2_trt, rho_ic=rho_ic, r21=r21, g3=g3, p=p, n=n, J=J, ic_size=ic_size, K0=K0, tol=tol), df=df, ncp = M, K = K) class(K.out) <- c ("main", "mrss") cat("K =", K, "\n") return(invisible(K.out)) }
"abstracts" "abstracts_dfm" "abstracts_dictionary" "abstracts_keyatm" "abstracts_warplda" "abstracts_btm" "afinn" "trump2k" "newsgroup_nb" NULL utils::globalVariables(c('cookd', 'diffxy', 'index', 'meanxy', 'word_length', 'avg_answer', 'abstracts_keyatm', 'abstracts')) .cp <- function(boolean_test, ...) { if (boolean_test) { cli::cli_alert_info(paste0(...)) } } .cstop <- function(boolean_test, ...) { if (boolean_test) { stop(..., call. = FALSE) } } .safe_sample <- function(x, size) { if (length(x) == 1) { return(x) } else { return(sample(x, size)) } } .generate_meta <- function() { list("package-version" = utils::packageVersion("oolong"), "r-version" = getRversion(), "system" = Sys.info()[c("sysname", "machine", "user")], "directory" = getwd(), "created" = Sys.Date() ) } .sym_flip <- function(bool) { ifelse(bool, cli::symbol$tick, cli::symbol$cross) } .safe_hash <- function(x) { if (is.null(x)) { return(NULL) } return(digest::digest(x, algo = "sha1")) }
library("matrixStats") source("utils/validateIndicesFramework.R") x <- runif(6, min = -6, max = 6) storage.mode(x) <- "integer" for (idxs in index_cases) { validateIndicesTestVector(x, idxs, ftest = product, fsure = prod, na.rm = TRUE) validateIndicesTestVector(x, idxs, ftest = product, fsure = prod, na.rm = FALSE) }
byosrmRoute <- function(src_dst, crs){ EPP::osrm_ok() getOption("osrm.server") == "https://routing.openstreetmap.de/" pop_s <- SpatialPoints(src_dst[ ,1:2], proj4string = crs) centers_s <- SpatialPoints(src_dst[ ,3:4], proj4string = crs) pop_s <- spTransform(pop_s, sp::CRS("+init=epsg:4326")) centers_s <- spTransform(centers_s, sp::CRS("+init=epsg:4326")) pop1 <- as.data.frame(cbind(1:nrow(src_dst), pop_s@coords)) centers1 <- as.data.frame(cbind(1:nrow(src_dst), centers_s@coords)) r <- as.list(NA) for (i in 1:nrow(pop1)) { tryCatch({ r[[i]] <- osrmRoute(src = pop1[i, ], dst = centers1[i, ], overview = "full", returnclass = "sp") src_dst[i, "dist"] <- r[[i]]@data$distance * 1000 src_dst[i, "time"] <- r[[i]]@data$duration }, error = function(e) {cat("ERROR :",conditionMessage(e), "\n")}) } src_dst }
ggdist::theme_ggdist ggdist::theme_tidybayes ggdist::facet_title_left_horizontal ggdist::facet_title_right_horizontal ggdist::axis_titles_bottom_left
source("ESEUR_config.r") library("plyr") pal_col=rainbow(3) proj_totals=function(df) { sloc=sum(df$sloc) methods=nrow(df) files=length(unique(df$file)) return(data.frame(sloc, methods, files)) } meth_per_file=function(df) { meth=ddply(df, .(file), function(df) return(nrow(df))) return(meth) } cc_loc=read.csv(paste0(ESEUR_dir, "sourcecode/Landman.csv.xz"), as.is=TRUE) cc_loc$logloc=log(cc_loc$sloc) proj_info=ddply(cc_loc, .(project), proj_totals) t=density(log(proj_info$sloc)) plot(exp(t$x), t$y, type="l", log="x", col=pal_col[1], xaxs="i", yaxs="i", ylim=c(0, 0.28), xlab="Total per project", ylab="Density\n") t=density(log(proj_info$methods)) lines(exp(t$x), t$y, col=pal_col[2]) t=density(log(proj_info$files)) lines(exp(t$x), t$y, col=pal_col[3]) legend(x="topright", legend=c("SLOC", "Methods", "Files"), bty="n", fill=pal_col, cex=1.2)
context("SP_LOG_REG") set.seed(SEED) options(bigstatsr.downcast.warning = FALSE) if (not_cran) { N <- 934 M <- 1053 m <- 30 x <- matrix(rnorm(N * M, mean = 100, sd = 5), N) set <- sample(M, size = m) eff <- rnorm(m) s <- drop(scale(x[, set]) %*% eff) / m y0 <- s + rnorm(N) / 10 y <- as.numeric(y0 > 0) y2 <- y; y2[] <- 0 y3 <- y; y3[10] <- NA covar0 <- matrix(rnorm(N * 3), N) lcovar <- list(NULL, covar0) test_that("can be used with a subset of samples", { for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x, TRUE), big_copy(x, type = t)) for (covar in sample(lcovar, 1)) { expect_error(big_spLogReg(X, y0, covar.train = covar, ncores = test_cores()), "'y01.train' should be composed of 0s and 1s.", fixed = TRUE) expect_error(big_spLogReg(X, y2, covar.train = covar, ncores = test_cores()), "'y01.train' should be composed of 0s and 1s.", fixed = TRUE) expect_error(big_spLogReg(X, y3, covar.train = covar, ncores = test_cores()), "'y01.train' should be composed of 0s and 1s.", fixed = TRUE) ind <- sample(N, N / 2) alphas <- c(runif(1, min = 0.1, max = 1), 1) mod.bigstatsr <- big_spLogReg(X, y, covar.train = covar, alphas = alphas, dfmax = Inf, nlam.min = Inf, warn = FALSE, ncores = test_cores()) lapply(mod.bigstatsr, function(mod) lapply(mod, function(fold) { if (fold$message != "Model saturated") expect_length(fold$lambda, 200) })) if (is.null(covar)) { expect_length(predict(mod.bigstatsr[2], X, ind.row = (1:N)[-ind], ncores = test_cores()), N / 2) } else { expect_error(predict(mod.bigstatsr[2], X, ind.row = (1:N)[-ind]), "You forgot to provide 'covar.row' in predict().") } preds <- predict(mod.bigstatsr, X, ind.row = (1:N)[-ind], covar.row = covar[-ind, ], ncores = test_cores()) expect_gt(AUC(preds, y[-ind]), 0.85) expect_s3_class(plot(mod.bigstatsr), "ggplot") mod.bigstatsr2 <- big_spLogReg(X, y[ind], ind.train = ind, covar.train = covar[ind, ], alphas = alphas, ncores = test_cores(), warn = FALSE) preds2 <- predict(mod.bigstatsr2, X, ind.row = (1:N)[-ind], covar.row = covar[-ind, ], ncores = test_cores()) expect_gt(AUC(preds2, y[-ind]), 0.7) expect_error(predict(mod.bigstatsr2, X, covar.row = covar, abc = 2), "Argument 'abc' not used.") flatten <- unlist(mod.bigstatsr2, recursive = FALSE) expect_true(all(sapply(flatten, class) == "big_sp")) lapply(flatten, function(obj) { expect_false(is.null(nb_candidate <- obj$nb_candidate)) expect_false(is.unsorted(nb_candidate)) expect_true(all(nb_candidate >= obj$nb_active)) }) } } }) test_that("can be used with a subset of variables (and penalty factors work)", { for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x, TRUE), big_copy(x, type = t)) ind.col <- cols_along(X)[-set] ind.novar <- sample(ind.col, 10); X[, ind.novar] <- 100 set2 <- match(set, (1:M)[-ind.novar]) for (covar in sample(lcovar, 1)) { ind <- sample(N, N / 2) alphas <- c(runif(1, min = 0.1, max = 1), 1) expect_warning( mod.bigstatsr3 <- big_spLogReg(X, y[ind], ind.train = ind, ind.col = ind.col, covar.train = covar[ind, ], alphas = alphas, ncores = test_cores(), warn = FALSE), "10 variables with low/no variation have been removed.", fixed = TRUE ) expect_equal(nrow(summary(mod.bigstatsr3)), length(alphas)) preds3 <- predict(mod.bigstatsr3, X, ind.row = (1:N)[-ind], covar.row = covar[-ind, ], ncores = test_cores()) expect_lt(AUC(preds3, y[-ind]), 0.7) expect_warning( mod.bigstatsr4 <- big_spLogReg(X, y[ind], ind.train = ind, covar.train = covar[ind, ], alphas = alphas, ncores = test_cores(), warn = FALSE), "10 variables with low/no variation have been removed.", fixed = TRUE ) expect_equal(length(attr(mod.bigstatsr4, "ind.col")), M - 10) expect_lte(length(mod.bigstatsr4[[c(1, 1)]]$beta), M - 10 + ncol(covar0)) preds4 <- predict(mod.bigstatsr4, X, ind.row = (1:N)[-ind], covar.row = covar[-ind, ], ncores = test_cores()) auc0 <- AUC(preds4, y[-ind]) pf <- rep(1, ncol(X)); pf[set] <- 10 expect_warning( mod.bigstatsr5 <- big_spLogReg(X, y[ind], ind.train = ind, covar.train = covar[ind, ], alphas = alphas, pf.X = pf, ncores = test_cores(), warn = FALSE), "10 variables with low/no variation have been removed.", fixed = TRUE ) preds5 <- predict(mod.bigstatsr5, X, ind.row = (1:N)[-ind], covar.row = covar[-ind, ], ncores = test_cores()) expect_lt(AUC(preds5, y[-ind]), auc0) pf[set] <- 0 expect_warning( mod.bigstatsr6 <- big_spLogReg(X, y[ind], ind.train = ind, covar.train = covar[ind, ], alphas = alphas, pf.X = pf, ncores = test_cores(), warn = FALSE), "10 variables with low/no variation have been removed.", fixed = TRUE ) lapply(unlist(mod.bigstatsr6, recursive = FALSE), function(mod) expect_true(all(mod$beta[set2] != 0))) preds6 <- predict(mod.bigstatsr6, X, ind.row = (1:N)[-ind], covar.row = covar[-ind, ], ncores = test_cores()) expect_gt(AUC(preds6, y[-ind]), auc0) } } }) test_that("parameter 'return.all' is deprecated and loss is correct", { for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x, TRUE), big_copy(x, type = t)) for (covar in sample(lcovar, 1)) { alpha <- runif(1, min = 0.01, max = 1) expect_warning(big_spLogReg(X, y, covar.train = covar, alphas = alpha, return.all = TRUE, warn = FALSE, ncores = test_cores())) mod.bigstatsr4 <- big_spLogReg(X, y, covar.train = covar, alphas = alpha, warn = FALSE, ncores = test_cores()) expect_length(mod.bigstatsr4, 1) flatten <- mod.bigstatsr4[[1]] expect_true(all(sapply(flatten, class) == "big_sp")) lapply(flatten, function(obj) { ind.val <- setdiff(rows_along(X), obj$ind.train) y.val <- y[ind.val] preds <- predict(obj, X, ind.row = ind.val, ind.col = attr(mod.bigstatsr4, "ind.col"), covar.row = covar[ind.val, ]) p <- 1 / (1 + exp(-preds)) loss.val <- -mean(y.val * log(p) + (1 - y.val) * log(1 - p)) diff <- abs(loss.val - obj$loss.val) expect_true(any(diff < 1e-8)) }) } } }) test_that("Use a base predictor", { for (t in TEST.TYPES) { X <- `if`(t == "raw", asFBMcode(x, TRUE), big_copy(x, type = t)) for (covar in sample(lcovar, 1)) { ind <- sample(N, N / 2) alphas <- c(runif(1, min = 0.01, max = 1), 1) ind.sets <- sample(rep_len(1:10, length(ind))) mod.bigstatsr <- big_spLogReg(X, y[ind], ind.train = ind, covar.train = covar[ind, ], alphas = alphas, ind.sets = ind.sets, ncores = test_cores(), warn = FALSE) preds <- predict(mod.bigstatsr, X, covar.row = covar, ncores = test_cores()) expect_gt(AUC(preds[-ind], y[-ind]), 0.7) mod.bigstatsr2 <- big_spLogReg(X, y[ind], ind.train = ind, base.train = rep(5, length(ind)), covar.train = covar[ind, ], alphas = alphas, ind.sets = ind.sets, ncores = test_cores(), warn = FALSE) expect_equal(sapply(unlist(mod.bigstatsr2, recursive = FALSE), function(x) x$intercept) + 5, sapply(unlist(mod.bigstatsr, recursive = FALSE), function(x) x$intercept)) expect_equal(sapply(unlist(mod.bigstatsr2, recursive = FALSE), function(x) x$beta.X), sapply(unlist(mod.bigstatsr, recursive = FALSE), function(x) x$beta.X)) mod.bigstatsr3 <- big_spLogReg(X, y[ind], ind.train = ind, base.train = preds[ind] / 2, covar.train = covar[ind, ], alphas = alphas, ind.sets = ind.sets, ncores = test_cores(), warn = FALSE) expect_error(predict(mod.bigstatsr3, X, covar.row = covar), "You forgot to provide 'base.row' in predict().") preds3 <- predict(mod.bigstatsr3, X, covar.row = covar, base.row = rep(0, N), ncores = test_cores()) expect_gt(cor(preds3, preds), 0.9) } } }) } test_that("Warns if not all converged", { skip_if_not(not_cran) set.seed(1) N <- 230 M <- 730 X <- FBM(N, M, init = rnorm(N * M, sd = 5)) y01 <- as.numeric((rowSums(X[, 1:10]) + 2 * rnorm(N)) > 0) covar <- matrix(rnorm(N * 3), N) ind.train <- sort(sample(nrow(X), 150)) ind.test <- setdiff(rows_along(X), ind.train) ALPHAS <- c(1, 0.5, 0.1, 0.01) expect_warning( test <- big_spLogReg(X, y01[ind.train], ind.train = ind.train, covar.train = covar[ind.train, ], alphas = ALPHAS, K = 4), "Some models may not have reached a minimum", fixed = TRUE ) test_summary <- summary(test) expect_identical(test_summary$alpha, sort(ALPHAS)) expect_identical(test_summary$all_conv, c(FALSE, FALSE, TRUE, TRUE)) test_summary2 <- summary(test, sort = TRUE) expect_identical(test_summary2$alpha, ALPHAS) expect_identical(test_summary2$all_conv, c(TRUE, TRUE, FALSE, FALSE)) expect_false(is.unsorted(test_summary2$validation_loss)) }) test_that("code is used for FBM.code256", { N <- 230 M <- 730 X <- FBM.code256(N, M, init = round(100 + rnorm(N * M, sd = 5)), code = rnorm(256)) y01 <- as.numeric((rowSums(X[, 1:10]) + rnorm(N)) > 0) covar <- matrix(rnorm(N * 3), N) test <- big_spLogReg(X, y01, K = 5) X2 <- X$copy(code = -X$code256) test2 <- big_spLogReg(X2, y01, K = 5) expect_lt(print(cor(summary(test)$beta[[1]], summary(test2)$beta[[1]])), -0.7) }) test_that("New power parameters work", { skip_if_not(not_cran) set.seed(1) N <- 230 M <- 730 X <- FBM(N, M, init = rnorm(N * M, sd = 5)) y01 <- as.numeric((rowSums(X[, 1:10]) + 2 * rnorm(N)) > 0) covar <- matrix(rnorm(N * 3), N) ind.train <- sort(sample(nrow(X), 150)) ind.test <- setdiff(rows_along(X), ind.train) ALPHAS <- c(1, 0.5, 0.1, 0.01) expect_warning( test <- big_spLogReg(X, y01[ind.train], ind.train = ind.train, covar.train = covar[ind.train, ], K = 4, alphas = ALPHAS, power_scale = c(0, 0.5, 1), power_adaptive = c(0, 0.5, 1.5)), "Some models may not have reached a minimum", fixed = TRUE ) test_summary <- summary(test) expect_identical(test_summary$alpha, rep(sort(ALPHAS), each = 9)) library(dplyr) nb_var <- test_summary %>% group_by(alpha, power_adaptive) %>% summarise(nb_var = mean(nb_var)) %>% ungroup() nb_var %>% group_by(alpha) %>% summarise(cor = cor(power_adaptive, nb_var, method = "spearman")) %>% pull(cor) %>% expect_equal(rep(-1, 4)) nb_var %>% group_by(power_adaptive) %>% summarise(cor = cor(alpha, nb_var, method = "spearman")) %>% pull(cor) %>% expect_equal(rep(-1, 3)) })
compar.lynch <- function(x, G, eps = 1e-4) { if (is.vector(x) || is.data.frame(x)) x <- as.matrix(x) alea <- runif(1, 0, 1) z <- as.vector(x) uz <- apply(x, 2, mean) vcvz <- var(x) vz <- diag(vcvz) nsp <- nrow(x) k <- ncol(x) X1 <- matrix(0, k, k) diag(X1) <- 1 I <- matrix(0, nsp, nsp) diag(I) <- 1 vara <- trvare <- matrix(NA, k, k) nsp1 <- rep(1, nsp) X <- X1 %x% nsp1 compteur <- 0 vara <- A0 <- alea * vcvz vare <- E0 <- (1 - alea) * vcvz newu <- u0 <- uz Ginv <- solve(G) V0 <- vcvz %x% G a0 <- e0 <- matrix(0, nsp, k) a1 <- e1 <- matrix(1, nsp, k) while (any(abs((rbind(a1, e1) - rbind(a0, e0))) > eps)) { a1 <- a0 e1 <- e0 compteur <- compteur + 1 Rinv <- solve(E0 %x% I) Dinv <- solve(A0 %x% G) info <- solve(Rinv + Dinv) newa <- solve(Rinv + Dinv) %*% Rinv %*% (z - X %*% u0) newe <- z - X %*% u0 - newa e0 <- mnewe <- matrix(newe, nsp, k) a0 <- mnewa <- matrix(newa, nsp, k) for (i in 1:k) { for (j in 1:k) { trvare[i, j] <- sum(diag(info[(((i - 1) * nsp) + 1):(i * nsp), (((j - 1) * nsp) + 1):(j * nsp)]))} } vare <- ((nsp - 1) * var(mnewe) + trvare) / nsp for (i in 1:k) { for (j in 1:k) { vara[i, j] <- (t(mnewa[, i]) %*% Ginv %*% mnewa[, j] + sum(diag(Ginv %*% info[(((i - 1) * nsp) + 1):(i * nsp), (((j - 1) * nsp) + 1):(j * nsp)]))) / nsp } } newu <- apply(x - mnewa, 2, mean) V <- vara %x% G + vare %x% I p <- (2 * pi)^(-nsp) * det(V)^(-0.5) * exp(-0.5 * t(z - (X %*% newu)) %*% solve(V) %*% (z - (X %*% newu))) E0 <- vare A0 <- vara u0 <- newu } dimnames(vare) <- dimnames(vara) list(vare = vare, vara = vara, A = mnewa, E = mnewe, u = newu, lik = log(p)) }
cut.ff <- function(x, breaks, ...){ f <- NULL if (length(breaks) == 1L) { if (is.na(breaks) || breaks < 2L) stop("invalid number of intervals") nb <- as.integer(breaks + 1) dx <- diff(rx <- range(x, na.rm = TRUE)) if (dx == 0) { dx <- abs(rx[1L]) breaks <- seq.int(rx[1L] - dx/1000, rx[2L] + dx/1000, length.out = nb) } else { breaks <- seq.int(rx[1L], rx[2L], length.out = nb) breaks[c(1L, nb)] <- c(rx[1L] - dx/1000, rx[2L] + dx/1000) } } else nb <- length(breaks <- sort.int(as.double(breaks))) if (anyDuplicated(breaks)) stop("'breaks' are not unique") args <- list(...) args$by <- NULL args$breaks <- breaks for (i in chunk(x, ...)){ Log$chunk(i) args$x <- x[i] res <- do.call(cut, args) f <- ffappend( f , res , adjustvmode=FALSE ) } f }
library(shiny.fluent) if (interactive()) { shinyApp( ui = tagList( reactOutput("modal"), PrimaryButton.shinyInput("showModal", text = "Show modal"), ), server = function(input, output) { modalVisible <- reactiveVal(FALSE) observeEvent(input$showModal, modalVisible(TRUE)) observeEvent(input$hideModal, modalVisible(FALSE)) output$modal <- renderReact({ Modal(isOpen = modalVisible(), Stack(tokens = list(padding = "15px", childrenGap = "10px"), div(style = list(display = "flex"), Text("Title", variant = "large"), div(style = list(flexGrow = 1)), IconButton.shinyInput("hideModal", iconProps = list(iconName = "Cancel")), ), div( p("A paragraph of text."), p("Another paragraph.") ) ) ) }) } ) }
iglu_shiny <- function() { appDir <- system.file('shiny_iglu', package = 'iglu') shiny::runApp(appDir, display.mode = 'normal') }
expected <- eval(parse(text="\"2014-03-17 18:47:59 GMT\"")); test(id=0, code={ argv <- eval(parse(text="list(structure(list(sec = 59.7693939208984, min = 47L, hour = 18L, mday = 17L, mon = 2L, year = 114L, wday = 1L, yday = 75L, isdst = 0L), .Names = c(\"sec\", \"min\", \"hour\", \"mday\", \"mon\", \"year\", \"wday\", \"yday\", \"isdst\"), class = c(\"POSIXlt\", \"POSIXt\"), tzone = \"GMT\"), \"%Y-%m-%d %H:%M:%S\", TRUE)")); .Internal(`format.POSIXlt`(argv[[1]], argv[[2]], argv[[3]])); }, o=expected);
entropy.shrink = function(y, lambda.freqs, unit=c("log", "log2", "log10"), verbose=TRUE) { f = freqs.shrink(y, lambda.freqs=lambda.freqs, verbose=verbose) h = entropy.plugin(f, unit=unit) attr(h, "lambda.freqs") = attr(f, "lambda.freqs") return( h ) } freqs.shrink = function (y, lambda.freqs, verbose = TRUE) { target = 1/length(y) n = sum(y) u = y/n if (missing(lambda.freqs)) { if (n==1 || n==0) { lambda.freqs = 1 } else { lambda.freqs = get.lambda.shrink(n, u, target, verbose) } } else { if (verbose) { cat(paste("Specified shrinkage intensity lambda.freq (frequencies):", round(lambda.freqs, 4)) , "\n") } } u.shrink = lambda.freqs * target + (1 - lambda.freqs) * u attr(u.shrink, "lambda.freqs") = lambda.freqs return(u.shrink) } mi.shrink = function(y2d, lambda.freqs, unit=c("log", "log2", "log10"), verbose=TRUE) { f2d = freqs.shrink(y2d, lambda.freqs=lambda.freqs, verbose=verbose) mi = mi.plugin(f2d, unit=unit) attr(mi, "lambda.freqs") = attr(f2d, "lambda.freqs") return( mi ) } chi2indep.shrink = function(y2d, lambda.freqs, unit=c("log", "log2", "log10"), verbose=TRUE) { f2d = freqs.shrink(y2d, lambda.freqs=lambda.freqs, verbose=verbose) chi2 = chi2indep.plugin(f2d, unit=unit) attr(chi2, "lambda.freqs") = attr(f2d, "lambda.freqs") return( chi2 ) } chi2.shrink = function(y1, y2, lambda.freqs1, lambda.freqs2, unit=c("log", "log2", "log10"), verbose=TRUE) { f1 = freqs.shrink(y1, lambda.freqs=lambda.freqs1, verbose=verbose) f2 = freqs.shrink(y2, lambda.freqs=lambda.freqs2, verbose=verbose) chi2 = chi2.plugin(f1, f2, unit=unit) attr(chi2, "lambda.freqs1") = attr(f1, "lambda.freqs") attr(chi2, "lambda.freqs2") = attr(f2, "lambda.freqs") return( chi2 ) } KL.shrink = function(y1, y2, lambda.freqs1, lambda.freqs2, unit=c("log", "log2", "log10"), verbose=TRUE) { f1 = freqs.shrink(y1, lambda.freqs=lambda.freqs1, verbose=verbose) f2 = freqs.shrink(y2, lambda.freqs=lambda.freqs2, verbose=verbose) KL = KL.plugin(f1, f2, unit=unit) attr(KL, "lambda.freqs1") = attr(f1, "lambda.freqs") attr(KL, "lambda.freqs2") = attr(f2, "lambda.freqs") return( KL ) } get.lambda.shrink = function(n, u, t, verbose) { varu = u*(1-u)/(n-1) msp = sum( (u-t)^2 ) if (msp == 0) { lambda = 1 } else lambda = sum( varu ) / msp if (lambda > 1) { lambda = 1 } if (lambda < 0) { lambda = 0 } if (verbose) { cat(paste("Estimating optimal shrinkage intensity lambda.freq (frequencies):", round(lambda, 4)) , "\n") } return(lambda) }
context("Ensuring that the `tab_footnote()` function works as expected") data <- mtcars %>% gt(rownames_to_stub = TRUE) %>% cols_move_to_start(columns = c("gear", "carb")) %>% tab_stubhead(label = "cars") %>% cols_hide(columns = "mpg") %>% cols_hide(columns = "vs") %>% tab_row_group( label = "Mercs", rows = contains("Merc"), ) %>% tab_row_group( label = "Mazdas", rows = contains("Mazda"), ) %>% tab_options(row_group.default_label = "Others") %>% tab_spanner( label = "gear_carb_cyl", id = "gcc", columns = c(gear, carb, cyl) ) %>% row_group_order(groups = c("Mazdas", "Mercs")) %>% cols_merge_range( col_begin = "disp", col_end = "drat" ) %>% tab_header( title = "Title", subtitle = "Subtitle" ) %>% tab_source_note(source_note = "this is a source note") %>% summary_rows( groups = c("Mazdas", "Mercs"), columns = c(hp, wt, qsec), fns = list( ~mean(., na.rm = TRUE), ~sum(., na.rm = TRUE)) ) %>% summary_rows( columns = c(hp, wt), fns = list( ~mean(., na.rm = TRUE), ~sum(., na.rm = TRUE)) ) data_2 <- gtcars %>% dplyr::filter(ctry_origin == "Germany") %>% dplyr::group_by(mfr) %>% dplyr::top_n(2, msrp) %>% dplyr::ungroup() %>% dplyr::select(mfr, model, drivetrain, msrp) %>% gt() %>% tab_spanner( label = "make and model", id = "mm", columns = c(mfr, model) ) %>% tab_spanner( label = "specs and pricing", id = "sp", columns = c(drivetrain, msrp) ) %>% tab_footnote( footnote = "Prices in USD.", locations = cells_column_labels(columns = msrp) ) %>% tab_footnote( footnote = "AWD = All Wheel Drive, RWD = Rear Wheel Drive.", locations = cells_column_labels(columns = drivetrain) ) %>% tab_footnote( footnote = "The most important details.", locations = cells_column_spanners(spanners = "sp") ) %>% tab_footnote( footnote = "German cars only.", locations = cells_column_spanners(spanners = "mm") ) data_3 <- gtcars %>% dplyr::filter(ctry_origin == "Germany") %>% dplyr::group_by(mfr) %>% dplyr::top_n(3, msrp) %>% dplyr::ungroup() %>% dplyr::select(mfr, model, drivetrain, msrp) %>% gt(rowname_col = "model", groupname_col = "mfr") %>% summary_rows( groups = c("BMW", "Audi"), columns = "msrp", fns = list( ~mean(., na.rm = TRUE), ~min(., na.rm = TRUE)) ) %>% summary_rows( columns = "msrp", fns = list( ~min(., na.rm = TRUE), ~max(., na.rm = TRUE)) ) %>% tab_footnote( footnote = "Average price for BMW and Audi.", locations = cells_summary( groups = c("BMW", "Audi"), columns = "msrp", rows = starts_with("me")) ) %>% tab_footnote( footnote = "Maximum price across all cars.", locations = cells_grand_summary( columns = "msrp", rows = starts_with("ma")) ) %>% tab_footnote( footnote = "Minimum price across all cars.", locations = cells_grand_summary( columns = "msrp", rows = starts_with("mi")) ) data_4 <- sp500 %>% dplyr::filter( date >= "2015-01-05" & date <="2015-01-10" ) %>% dplyr::select( -c(adj_close, volume, high, low) ) %>% gt() %>% tab_header( title = "S&P 500", subtitle = "Open and Close Values" ) %>% tab_footnote( footnote = "All values in USD.", locations = list( cells_title(groups = "subtitle") ) ) %>% tab_footnote( footnote = "Standard and Poor 500.", locations = list( cells_title(groups = "title") ) ) check_suggests <- function() { skip_if_not_installed("rvest") skip_if_not_installed("xml2") } selection_value <- function(html, key) { selection <- paste0("[", key, "]") html %>% rvest::html_nodes(selection) %>% rvest::html_attr(key) } selection_text <- function(html, selection) { html %>% rvest::html_nodes(selection) %>% rvest::html_text() } test_that("the `tab_footnote()` function works correctly", { check_suggests() tab <- data %>% tab_footnote( footnote = "Column labels and stub footnote.", locations = list( cells_column_labels(), cells_stub(rows = TRUE) ) ) dt_footnotes_get(data = tab) %>% dplyr::pull(locname) %>% unique() %>% expect_equal(c("columns_columns", "stub")) dt_footnotes_get(data = tab) %>% dplyr::pull(footnotes) %>% unique() %>% expect_equal("Column labels and stub footnote.") tab <- data %>% tab_footnote( footnote = "Stub cell footnote.", locations = cells_stub(rows = "Merc 240D") ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("stub", NA_character_, NA_character_, "5", "8", NA_character_, "Stub cell footnote.") ) tab <- data %>% tab_footnote( footnote = "Title footnote.", locations = cells_title(groups = "title") ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("title", NA_character_, NA_character_, "1", NA_character_, NA_character_, "Title footnote.") ) tab <- data %>% tab_footnote( footnote = "Subtitle footnote.", locations = cells_title(groups = "subtitle") ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("subtitle", NA_character_, NA_character_, "2", NA_character_, NA_character_, "Subtitle footnote.") ) tab <- data %>% tab_footnote( footnote = "Stubhead label footnote.", locations = cells_stubhead() ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("stubhead", NA_character_, NA_character_, "2.5", NA_character_, NA_character_, "Stubhead label footnote.") ) tab <- data %>% tab_footnote( footnote = "Summary cell footnote.", locations = cells_summary( groups = "Mercs", columns = "hp", rows = 2) ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("summary_cells", "Mercs", "hp", "5", "2", NA_character_, "Summary cell footnote.") ) expect_error( data %>% tab_footnote( footnote = "Summary cell footnote.", locations = cells_summary( groups = "Mercs", columns = starts_with("x"), rows = 2) ) ) expect_error( data %>% tab_footnote( footnote = "Summary cell footnote.", locations = cells_summary( groups = "Mercs", columns = starts_with("m"), rows = starts_with("x")) ) ) tab <- data %>% tab_footnote( footnote = "Grand summary cell footnote.", locations = cells_grand_summary( columns = wt, rows = starts_with("s") ) ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("grand_summary_cells", "::GRAND_SUMMARY", "wt", "6", "2", NA_character_, "Grand summary cell footnote.") ) expect_error( data %>% tab_footnote( footnote = "Grand summary cell footnote.", locations = cells_grand_summary( columns = starts_with("x"), rows = 2) ) ) expect_error( data %>% tab_footnote( footnote = "Grand summary cell footnote.", locations = cells_grand_summary( columns = starts_with("m"), rows = starts_with("x")) ) ) tab <- data %>% tab_footnote( footnote = "Summary cell footnote.", locations = cells_summary( groups = "Mercs", columns = "hp", rows = 2) ) %>% tab_footnote( footnote = "Grand summary cell footnote.", locations = cells_grand_summary( columns = wt, rows = starts_with("s") ) ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(2) expect_attr_equal( tab, "_footnotes", c("summary_cells", "grand_summary_cells", "Mercs", "::GRAND_SUMMARY", "hp", "wt", "5", "6", "2", "2", NA_character_, NA_character_, "Summary cell footnote.", "Grand summary cell footnote.") ) tab <- data %>% tab_footnote( footnote = "Group cell footnote.", locations = cells_row_groups(groups = "Mazdas")) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("row_groups", "Mazdas", NA_character_, "5", NA_character_, NA_character_, "Group cell footnote.") ) tab <- data %>% tab_footnote( footnote = "Column group footnote.", locations = cells_column_spanners(spanners = "gcc") ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("columns_groups", "gcc", NA_character_, "3", NA_character_, NA_character_, "Column group footnote.") ) tab <- data %>% tab_footnote( footnote = "Single column label footnote.", locations = cells_column_labels(columns = "gear") ) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("columns_columns", NA_character_, "gear", "4", NA_character_, NA_character_, "Single column label footnote.") ) tab <- data %>% tab_footnote( footnote = "Five rows footnote.", locations = cells_body(columns = "hp", rows = 1:5)) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(5) dt_footnotes_get(data = tab) %>% dplyr::pull(rownum) %>% expect_equal(1:5) dt_footnotes_get(data = tab) %>% dplyr::pull(footnotes) %>% unique() %>% expect_equal("Five rows footnote.") dt_footnotes_get(data = tab) %>% dplyr::pull(locname) %>% unique() %>% expect_equal("data") dt_footnotes_get(data = tab) %>% dplyr::pull(colname) %>% unique() %>% expect_equal("hp") expect_error( data %>% tab_footnote( footnote = "Footnote error.", locations = cells_body(columns = "disp", rows = "Mazda RX7"))) tab <- data %>% tab_footnote( footnote = "A footnote.", locations = cells_body(columns = "disp", rows = c("Mazda RX4"))) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(1) dt_footnotes_get(data = tab) %>% unlist() %>% unname() %>% expect_equal( c("data", NA_character_, "disp", "5", "1", NA_character_, "A footnote.")) tab <- data %>% tab_footnote( footnote = "A footnote.", locations = cells_body(columns = c(disp, hp), rows = "Mazda RX4")) dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(2) dt_footnotes_get(data = tab)[1, ] %>% unlist() %>% unname() %>% expect_equal(c( "data", NA_character_, "disp", "5", "1", NA_character_, "A footnote.")) dt_footnotes_get(data = tab)[2, ] %>% unlist() %>% unname() %>% expect_equal(c( "data", NA_character_, "hp", "5", "1", NA_character_, "A footnote.")) tab <- data_2 dt_footnotes_get(data = tab) %>% nrow() %>% expect_equal(4) dt_footnotes_get(data = tab) %>% dplyr::pull(locname) %>% unique() %>% expect_equal(c("columns_columns", "columns_groups")) tbl_html <- tab %>% render_as_html() %>% xml2::read_html() tbl_html %>% selection_text(selection = "[class='gt_footnote']") %>% tidy_gsub("\n ", "") %>% expect_equal( c( "1 German cars only.", "2 The most important details.", "3 AWD = All Wheel Drive, RWD = Rear Wheel Drive.", "4 Prices in USD.") ) tbl_html %>% selection_text(selection = "[class='gt_footnote_marks']") %>% tidy_gsub("\n ", "") %>% expect_equal(rep(as.character(1:4), 2)) }) test_that("the footnotes table is structured correctly", { footnotes_tbl <- dt_footnotes_get(data = data_3) expect_is(footnotes_tbl, "tbl_df") expect_equal( colnames(footnotes_tbl), c("locname", "grpname", "colname", "locnum", "rownum", "colnum", "footnotes") ) expect_equal(nrow(footnotes_tbl), 4) expect_equal( footnotes_tbl$locname, c("summary_cells", "summary_cells", "grand_summary_cells", "grand_summary_cells") ) expect_equal(footnotes_tbl$locnum, c(5, 5, 6, 6)) expect_equal(footnotes_tbl$grpname, c("BMW", "Audi", "::GRAND_SUMMARY", "::GRAND_SUMMARY")) expect_equal(footnotes_tbl$colname, rep("msrp", 4)) expect_equal(footnotes_tbl$colnum, rep(NA_integer_, 4)) expect_equal( footnotes_tbl$footnotes, c("Average price for BMW and Audi.", "Average price for BMW and Audi.", "Maximum price across all cars.", "Minimum price across all cars.") ) footnotes_tbl <- dt_footnotes_get(data = data_4) expect_is(footnotes_tbl, "tbl_df") expect_equal( colnames(footnotes_tbl), c("locname", "grpname", "colname", "locnum", "rownum", "colnum", "footnotes") ) expect_equal(nrow(footnotes_tbl), 2) expect_equal(footnotes_tbl$locname, c("subtitle", "title")) expect_equal(footnotes_tbl$grpname, c(NA_character_, NA_character_)) expect_equal(footnotes_tbl$colname, c(NA_character_, NA_character_)) expect_equal(footnotes_tbl$locnum, c(2, 1)) expect_equal(footnotes_tbl$rownum, c(NA_integer_, NA_integer_)) expect_equal(footnotes_tbl$colnum, c(NA_integer_, NA_integer_)) expect_equal( footnotes_tbl$footnotes, c("All values in USD.", "Standard and Poor 500.") ) tbl_html <- data_4 %>% render_as_html() %>% xml2::read_html() tbl_html %>% selection_text(selection = "[class='gt_heading gt_title gt_font_normal']") %>% expect_equal("S&P 5001") tbl_html %>% selection_text(selection = "[class='gt_heading gt_subtitle gt_font_normal gt_bottom_border']") %>% expect_equal("Open and Close Values2") }) test_that("the `list_of_summaries` table is structured correctly", { gtcars_built <- gtcars %>% dplyr::filter(ctry_origin == "Germany") %>% dplyr::group_by(mfr) %>% dplyr::top_n(3, msrp) %>% dplyr::ungroup() %>% dplyr::select(mfr, model, drivetrain, msrp) %>% gt(rowname_col = "model", groupname_col = "mfr") %>% summary_rows( groups = c("BMW", "Audi"), columns = msrp, fns = list( ~mean(., na.rm = TRUE), ~min(., na.rm = TRUE)) ) %>% summary_rows( columns = msrp, fns = list( ~min(., na.rm = TRUE), ~max(., na.rm = TRUE)) ) %>% build_data(context = "html") gtcars_built_summary_df <- dt_summary_df_get(data = gtcars_built) gtcars_built_summary_df_data <- dt_summary_df_data_get(data = gtcars_built) gtcars_built_summary_df_display <- dt_summary_df_display_get(data = gtcars_built) expect_equal(length(gtcars_built_summary_df), 2) expect_equal( names(gtcars_built_summary_df), c("summary_df_data_list", "summary_df_display_list") ) expect_equal(length(gtcars_built_summary_df_data$summary_df_data_list), 3) expect_equal(length(gtcars_built_summary_df_display$summary_df_display_list), 3) expect_equal( names(gtcars_built_summary_df_data$summary_df_data_list), c("BMW", "Audi", "::GRAND_SUMMARY") ) expect_equal( names(gtcars_built_summary_df_display$summary_df_display_list), c("::GRAND_SUMMARY", "Audi", "BMW") ) expect_equal( gtcars_built_summary_df_display$summary_df_display_list$`::GRAND_SUMMARY`$msrp, c("56,000.00", "140,700.00") ) expect_equal( gtcars_built_summary_df_display$summary_df_display_list$Audi$msrp, c("113,233.33", "108,900.00") ) expect_equal( gtcars_built_summary_df_display$summary_df_display_list$BMW$msrp, c("116,066.67", "94,100.00") ) })
"pj_officer_level_balanced"
massLoss <- function( dat, time.name, m.pre.name = NULL, m.post.name, id.name ) { dat <- dat[order(dat[, id.name], dat[, time.name]), ] for(i in unique(dat[, id.name])) { which.id <- which(dat[, id.name]==i) n.id <- length(which.id) dat[which.id, 'mass.tot'] <- c(0, -diff(dat[which.id, m.post.name])) dat[which.id, 'cmass.tot'] <- cumsum(dat[which.id, 'mass.tot']) if (!is.null(m.pre.name)) { dat[which.id, 'mass.vent'] <- dat[which.id, m.pre.name] - dat[which.id, m.post.name] dat[which.id, 'mass.leak'] <- c(0, dat[which.id, m.post.name][-n.id] - dat[which.id, m.pre.name][-1]) dat[which.id, 'cmass.vent'] <- cumsum(dat[which.id, 'mass.vent']) dat[which.id, 'cmass.leak'] <- cumsum(dat[which.id, 'mass.leak']) } } return(dat) }
M <- function(startValue = NULL, iterations = 10000, nBI = 0 , parmin = NULL, parmax= NULL, f = 1, FUN, consoleUpdates=1000) { if(class(FUN) == "BayesianSetup"){ if(FUN$numPars==1) stop("Sampler cannot be started for 1 parameter") if(is.null(startValue)){ startValue <- FUN$prior$sampler() } parmin <- FUN$prior$lower parmax <- FUN$prior$upper FUN <- FUN$posterior$density } pValues = startValue lChain = iterations npar <- length(pValues) logMAP <- -Inf pChain <- matrix(NA_real_, nrow = lChain - nBI, ncol = npar+3) postL0 <- FUN(pValues, returnAll = T) accept.prob <- 0 scalProp <- f * 2.4^2/npar covPar <- scalProp * diag((0.01 * (parmax - parmin))^2) for (j in 1:lChain) { if (j%%consoleUpdates == 0) print(c(j,postL1[1])) candidatepValues <- mvtnorm::rmvnorm(1, pValues, covPar) postL1 <- FUN(candidatepValues, returnAll = T) alpha <- min(exp(postL1[1] - postL0[1]), 1) accept <- 0 if (runif(1) < alpha) { postL0 <- postL1 pValues <- candidatepValues accept <- 1 if (postL0[1] > logMAP) { logMAP <- postL0[1] psetMAP <- pValues } } if (j > nBI) { pChain[j-nBI,] <- c(pValues,postL0) accept.prob <- accept.prob + accept } } accept.prob <- accept.prob/(lChain-nBI) list(Draws = pChain, accept.prob = accept.prob,psetMAP=psetMAP) } AM <- function(startValue = NULL, iterations = 10000, nBI = 0, parmin = NULL, parmax = NULL, FUN, f = 1, eps = 0) { if(class(FUN) == "BayesianSetup"){ if(FUN$numPars==1) stop("Sampler cannot be started for 1 parameter") if(is.null(startValue)){ startValue <- FUN$prior$sampler() } parmin <- FUN$prior$lower parmax <- FUN$prior$upper FUN <- FUN$posterior$density } pValues = startValue lChain = iterations noAdapt <- 1000 n.iter <- lChain + noAdapt npar = length(pValues) pChain <- matrix(NA_real_, nrow = n.iter - nBI, ncol = npar+3) postL0 <- FUN(pValues, returnAll = T) accept.prob <- 0 epsDiag <- eps * diag(npar) scalProp <- f * (2.4^2/npar) covPar <- scalProp * diag((0.01*(parmax - parmin))^2) for (j in 1:n.iter) { candidatepValues <- as.vector(mvtnorm::rmvnorm(1, pValues, covPar)) postL1 <- FUN(candidatepValues, returnAll = T) alpha <- min(exp(postL1[1] - postL0[1]), 1) accept <- 0 if (runif(1) < alpha) { postL0 <- postL1 pValues <- candidatepValues accept <- 1 } if (j > nBI) { pChain[j-nBI,] <- c(pValues, postL0) } if (j == (nBI + noAdapt)) { avePar <- apply(pChain[1:noAdapt,1:npar], 2, mean) covPar <- scalProp * (cov(pChain[1:noAdapt,1:npar], pChain[1:noAdapt,1:npar]) + epsDiag) } if (j > (nBI + noAdapt)) { accept.prob <- accept.prob + accept t <- j - nBI avePar_new <- as.vector(((t-1) * avePar + pValues) / t) covPar_new <- ((t-2) * covPar + scalProp * ((t-1) * (avePar %o% avePar) - t * (avePar_new %o% avePar_new) + (pValues %o% pValues)) + epsDiag) / (t-1) avePar <- avePar_new covPar <- covPar_new } } accept.prob = accept.prob/(lChain-nBI) list(Draws = pChain[(noAdapt+1):(n.iter-nBI),], accept.prob = accept.prob) } DR <- function(startValue = NULL, iterations = 10000, nBI=0, parmin = NULL, parmax =NULL, f1 = 1, f2= 0.5, FUN) { if(class(FUN) == "BayesianSetup"){ if(FUN$numPars==1) stop("Sampler cannot be started for 1 parameter") if(is.null(startValue)){ startValue <- FUN$prior$sampler() } parmin <- FUN$prior$lower parmax <- FUN$prior$upper FUN <- FUN$posterior$density } pValues = startValue lChain = iterations npar = length(pValues) pChain <- matrix(NA_real_, nrow = lChain - nBI, ncol = npar+3) postL0 <- FUN(pValues, returnAll = T) covPar <- diag((0.01 * (parmax - parmin))^2) sP <- (2.4^2/npar) * c(f1, f2) accept.prob <- 0 for (j in 1:lChain) { candidatepValues <- mvtnorm::rmvnorm(1, pValues, sP[1] * covPar) postL1 <- FUN(candidatepValues, returnAll = T) alpha1 <- min(exp(postL1[1]-postL0[1]), 1.0) accept <- 0 if (runif(1) < alpha1) { pValues <- candidatepValues postL0 = postL1 accept <- 1 } else { candidatepValues2 <- mvtnorm::rmvnorm(1, pValues, sP[2] * covPar) postL2 <- FUN(candidatepValues2, returnAll = T) alpha2 <- min(exp(postL1[1]-postL2[1]), 1.0) temp <- mvtnorm::dmvnorm(candidatepValues, candidatepValues2, sP[1] * covPar) / mvtnorm::dmvnorm(candidatepValues, pValues, sP[1] * covPar) alpha <- min(exp(postL2[1]-postL0[1]) * temp * ((1.0-alpha2)/(1.0-alpha1)), 1.0) if(is.nan(alpha)) { alpha <- -1 } if (runif(1) < alpha) { pValues <- candidatepValues2 postL0 <- postL2 accept <- 1 } } if (j > nBI) { pChain[j-nBI,] <- c(pValues, postL0) accept.prob <- accept.prob + accept } } accept.prob = accept.prob/(lChain-nBI) list(Draws = pChain, accept.prob = accept.prob) } DRAM <- function(startValue = NULL, iterations = 10000, nBI = 0, parmin = NULL, parmax = NULL, FUN, f = 1, eps = 0) { if(class(FUN) == "BayesianSetup"){ if(FUN$numPars==1) stop("Sampler cannot be started for 1 parameter") if(is.null(startValue)){ startValue <- FUN$prior$sampler() } parmin <- FUN$prior$lower parmax <- FUN$prior$upper FUN <- FUN$posterior$density } pValues = startValue lChain = iterations noAdapt <- 1000 n.iter <- lChain + noAdapt npar = length(pValues) pChain <- matrix(NA_real_, nrow = n.iter - nBI, ncol = npar+3) postL0 <- FUN(pValues, returnAll = T) accept.prob <- 0 epsDiag <- eps * diag(npar) scalProp <- f * (2.4^2/npar) covPar <- scalProp * diag((0.01*(parmax - parmin))^2) for (j in 1:n.iter) { candidatepValues <- as.vector(mvtnorm::rmvnorm(1, pValues, covPar)) postL1 <- FUN(candidatepValues, returnAll = T) alpha1 <- min(exp(postL1[1] - postL0[1]), 1) accept <- 0 if (runif(1) < alpha1) { postL0 <- postL1 pValues <- candidatepValues accept <- 1 } else { candidatepValues2 <- as.vector(mvtnorm::rmvnorm(1, pValues, 0.5 * covPar)) postL2 <- FUN(candidatepValues2, returnAll = T) alpha2 <- min(exp(postL1[1]-postL2[1]), 1.0) temp <- mvtnorm::dmvnorm(candidatepValues, candidatepValues2, covPar) / mvtnorm::dmvnorm(candidatepValues, pValues, covPar) alpha <- min(exp(postL2[1]-postL0[1]) * temp * ((1.0-alpha2)/(1.0-alpha1)), 1.0) if(is.nan(alpha)) { alpha <- -1 } if (runif(1) < alpha) { pValues <- candidatepValues2 postL0 <- postL2 accept <- 1 } } if (j > nBI) { pChain[j-nBI,] <- c(pValues, postL0) } if (j == (nBI + noAdapt)) { avePar <- apply(pChain[1:noAdapt,1:npar], 2, mean) covPar <- scalProp * (cov(pChain[1:noAdapt,1:npar], pChain[1:noAdapt,1:npar]) + epsDiag) } if (j > (nBI + noAdapt)) { accept.prob <- accept.prob + accept t <- j - nBI avePar_new <- as.vector(((t-1) * avePar + pValues) / t) covPar_new <- ((t-2) * covPar + scalProp * ((t-1) * (avePar %o% avePar) - t * (avePar_new %o% avePar_new) + (pValues %o% pValues)) + epsDiag) / (t-1) avePar <- avePar_new covPar <- covPar_new } } accept.prob = accept.prob/(lChain-nBI) list(Draws = pChain[(noAdapt+1):(n.iter-nBI),], accept.prob = accept.prob) }
mpi.hostinfo <- function(comm=1){ if (mpi.comm.size(comm)==0){ err <-paste("It seems no members running on comm", comm) stop(err) } hostname <- mpi.get.processor.name() rk <- mpi.comm.rank(comm=comm) size <- mpi.comm.size(comm=comm) cat("\tHost:",hostname,"\tRank(ID):",rk, "\tof Size:", size, "on comm", comm, "\n") } slave.hostinfo <- function(comm=1, short=TRUE){ if (mpi.comm.rank(comm)!=0) stop("cannot run slavehostinfo on slaves") size <- mpi.comm.size(comm) if (size==0){ err <-paste("It seems no slaves running on comm", comm) stop(err) } if (size == 1) mpi.hostinfo(comm) else { master <-mpi.get.processor.name() slavehost <- unlist(mpi.remote.exec(mpi.get.processor.name(),comm=comm)) slavecomm <- 1 ranks <- 1:(size-1) commm <- paste(comm, ")",sep="") if (size > 10){ rank0 <- paste("master (rank 0 , comm", commm) ranks <- c(paste(ranks[1:9]," ",sep=""), ranks[10:(size-1)]) } else rank0 <- paste("master (rank 0, comm", commm) cat(rank0, "of size", size, "is running on:",master, "\n") slavename <- paste("slave", ranks,sep="") ranks <- paste("(rank ",ranks, ", comm ",slavecomm,")", sep="") if (short && size > 8){ for (i in 1:3) { cat(slavename[i], ranks[i], "of size",size, "is running on:",slavehost[i], "\n") } cat("... ... ...\n") for (i in (size-2):(size-1)){ cat(slavename[i], ranks[i], "of size",size, "is running on:",slavehost[i], "\n") } } else { for (i in 1:(size-1)){ cat(slavename[i], ranks[i], "of size",size, "is running on:",slavehost[i], "\n") } } } } lamhosts <- function(){ hosts <- system("lamnodes C -c -n", TRUE) base <-character(0) for (host in hosts) base <- c(base, unlist(strsplit(host, "\\."))[1]) nn <- 0:(length(hosts)-1) names(nn) <- base nn } mpi.spawn.Rslaves <- function(Rscript=system.file("slavedaemon.R", package="Rmpi"), nslaves=mpi.universe.size(), root=0, intercomm=2, comm=1, hosts=NULL, needlog=TRUE, mapdrive=TRUE, quiet=FALSE, nonblock=TRUE, sleep=0.1) { if (!is.loaded("mpi_comm_spawn")) stop("You cannot use MPI_Comm_spawn API") if (mpi.comm.size(comm) > 0){ err <-paste("It seems there are some slaves running on comm ", comm) stop(err) } if (.Platform$OS=="windows"){ workdrive <- unlist(strsplit(getwd(),":"))[1] workdir <- unlist(strsplit(getwd(),"/")) if (length(workdir) > 1) workdir <-paste(workdir, collapse="\\") else workdir <- paste(workdir,"\\") localhost <- Sys.getenv("COMPUTERNAME") networkdrive <-NULL remotepath <-networkdrive[which(networkdrive=="RemotePath")+1] mapdrive <- as.logical(mapdrive && !is.null(remotepath)) arg <- c(Rscript, R.home(), workdrive, workdir, localhost, mapdrive, remotepath) if (.Platform$r_arch == "i386") realns <- mpi.comm.spawn(slave = system.file("Rslaves32.cmd", package = "Rmpi"), slavearg = arg, nslaves = nslaves, info = 0, root = root, intercomm = intercomm, quiet = quiet) else realns <- mpi.comm.spawn(slave = system.file("Rslaves64.cmd", package = "Rmpi"), slavearg = arg, nslaves = nslaves, info = 0, root = root, intercomm = intercomm, quiet = quiet) } else{ tmp <- paste(Sys.getpid(), "+", comm, sep="") if (needlog) arg <- c(Rscript, tmp, "needlog", R.home()) else arg <- c(Rscript, tmp , "nolog", R.home()) if (!is.null(hosts)){ hosts <- as.integer(hosts) if (any(is.na(hosts))) stop("hosts argument contains non-integer object(s).") if (max(hosts) > mpi.universe.size() -1 ||min(hosts) < 0){ tmp1 <- paste("hosts number should be within 0 to", mpi.universe.size()-1) stop(tmp1) } nslaves <- length(hosts) tmpfile <-paste(tmp, "appschema", sep="") fileobj <- file(tmpfile,"w") cat("c", paste(hosts, collapse=","), sep="", file=fileobj) cat(" ", system.file("Rslaves.sh", package="Rmpi"), file=fileobj) cat(" ", paste(arg, collapse=" "), file=fileobj) close(fileobj) mpi.info.create(0) mpi.info.set(0,"file",tmpfile) } if (length(unlist(strsplit(.Platform$pkgType,"mac"))) ==2 && .Platform$r_arch =="x86_64") realns<-mpi.comm.spawn(slave=system.file("MacR64slaves.sh", package="Rmpi"), slavearg=arg, nslaves=nslaves, info=0, root=root, intercomm=intercomm, quiet = quiet) else realns<-mpi.comm.spawn(slave=system.file("Rslaves.sh", package="Rmpi"), slavearg=arg, nslaves=nslaves, info=0, root=root, intercomm=intercomm, quiet = quiet) } if (!is.null(hosts)){ unlink(tmpfile) mpi.info.free(0) } if (realns==0) stop("It seems no single slave spawned.") if (mpi.intercomm.merge(intercomm,0,comm)) { mpi.comm.set.errhandler(comm) mpi.comm.disconnect(intercomm) mpi.bcast(nonblock,type=1, rank=0, comm=comm) mpi.bcast(sleep,type=2, rank=0, comm=comm) if (!quiet) slave.hostinfo(comm) } else stop("Fail to merge the comm for master and slaves.") } mpi.remote.exec <- function(cmd, ..., simplify=TRUE, comm=1, ret=TRUE){ if (mpi.comm.size(comm) < 2) stop("It seems no slaves running.") tag <- floor(runif(1,20000,30000)) scmd <- substitute(cmd) arg <-list(...) mpi.bcast.cmd(.mpi.worker.exec, tag=tag, ret=ret, simplify=simplify, comm = comm) mpi.bcast.Robj(list(scmd=scmd, arg=arg), comm=comm) if (ret){ size <- mpi.comm.size(comm) allcode <- mpi.allgather(integer(2), 1, integer(2*size), comm) type <- allcode[seq(3,2*size,2)] len <- allcode[seq(4,2*size,2)] eqlen <- all(len==len[1]) if (all(type==1)){ if (eqlen && simplify){ out <- mpi.gather(integer(len[1]),1,integer(size*len[1]),0,comm) out <- out[(len[1]+1):(size*len[1])] dim(out) <- c(len[1], size-1) out <- data.frame(out) } else { out1<-mpi.gatherv(integer(1),1,integer(1+sum(len)),c(1,len),0,comm) uplen <- cumsum(len)+1 lowlen <-c(2, uplen[-(size-1)]+1) out <- as.list(integer(size-1)) names(out) <- paste("slave",1:(size-1), sep="") for (i in 1:(size-1)) out[[i]]<- out1[lowlen[i]:uplen[i]] } } else if (all(type==2)){ if (eqlen && simplify){ out <- mpi.gather(double(len[1]),2,double(size*len[1]),0,comm) out <- out[(len[1]+1):(size*len[1])] dim(out) <- c(len[1], size-1) out <- data.frame(out) } else { out1<-mpi.gatherv(double(1),2,double(1+sum(len)),c(1,len),0,comm) uplen <- cumsum(len)+1 lowlen <-c(2, uplen[-(size-1)]+1) out <- as.list(integer(size-1)) names(out) <- paste("slave",1:(size-1), sep="") for (i in 1:(size-1)) out[[i]]<- out1[lowlen[i]:uplen[i]] } } else if (all(type==4)){ if (eqlen && simplify){ out <- mpi.gather(raw(len[1]),4,raw(size*len[1]),0,comm) out <- out[(len[1]+1):(size*len[1])] dim(out) <- c(len[1], size-1) out <- data.frame(out) } else { out1<-mpi.gatherv(raw(1),4,raw(1+sum(len)),c(1,len),0,comm) uplen <- cumsum(len)+1 lowlen <-c(2, uplen[-(size-1)]+1) out <- as.list(integer(size-1)) names(out) <- paste("slave",1:(size-1), sep="") for (i in 1:(size-1)) out[[i]]<- out1[lowlen[i]:uplen[i]] } } else { out <- as.list(integer(size-1)) names(out) <- paste("slave",1:(size-1), sep="") for (i in 1:(size-1)){ tmp<- mpi.recv.Robj(mpi.any.source(),tag,comm) src <- mpi.get.sourcetag()[1] out[[src]]<- tmp } } out } } .typeindex <- function (x) { if(class(x)=="integer") as.integer(c(1,length(x))) else if (class(x)=="numeric") as.integer(c(2,length(x))) else if (class(x)=="raw") as.integer(c(4,length(x))) else as.integer(-1) } .mpi.worker.exec <- function(tag, ret, simplify){ assign(".mpi.err", FALSE) .comm <- 1 scmd.arg <- mpi.bcast.Robj(comm=.comm) if (ret){ size <- mpi.comm.size(.comm) myerrcode <- as.integer(0) if (length(scmd.arg$arg)>0) out <- try(do.call(as.character(scmd.arg$scmd), scmd.arg$arg, envir=.GlobalEnv),TRUE) else out <- try(eval(scmd.arg$scmd, envir=sys.parent()), TRUE) if (get(".mpi.err")){ print(geterrmessage()) type <- integer(2) } else { type <- .typeindex(out) if (is.na(type[2])) type[2] <- as.integer(0) } allcode <- mpi.allgather(type, 1, integer(2*size), .comm) type <- allcode[seq(3,2*size,2)] len <- allcode[seq(4,2*size,2)] eqlen <- all(len==len[1]) if (all(type==1)) { if (eqlen && simplify) mpi.gather(out, 1, integer(1), 0, .comm) else mpi.gatherv(out, 1, integer(1), integer(1), 0 ,.comm) } else if (all(type==2)) { if (eqlen && simplify) mpi.gather(out, 2, double(1), 0, .comm) else mpi.gatherv(out, 2, double(1), integer(1), 0, .comm) } else if (all(type==4)) { if (eqlen && simplify) mpi.gather(out, 4, raw(1), 0, .comm) else mpi.gatherv(out, 4, raw(1), integer(1), 0, .comm) } else { mpi.send.Robj(out,0,tag,.comm) } } else { if (length(scmd.arg$arg)>0) out <- try(do.call(as.character(scmd.arg$scmd), scmd.arg$arg)) else out <- try(eval(scmd.arg$scmd)) } } mpi.close.Rslaves <- function(dellog=TRUE, comm=1){ if (mpi.comm.size(comm) < 2){ err <-paste("It seems no slaves running on comm", comm) stop(err) } mpi.bcast.cmd(cmd="kaerb", rank=0, comm=comm) if (.Platform$OS!="windows"){ if (dellog && mpi.comm.size(0) < mpi.comm.size(comm)){ tmp <- paste(Sys.getpid(),"+",comm,sep="") logfile <- paste("*.",tmp,".*.log", sep="") if (length(system(paste("ls", logfile),TRUE,ignore.stderr=TRUE) )>=1) system(paste("rm", logfile)) } } if (comm >0){ mpi.comm.free(comm) } } tailslave.log <- function(nlines=3,comm=1){ if (mpi.comm.size(comm)==0) stop ("It seems no slaves running") tmp <- paste(Sys.getpid(),"+",comm,sep="") logfile <- paste("*.",tmp,".*.log", sep="") if (length(system(paste("ls", logfile),TRUE,ignore.stderr=TRUE))==0) stop("It seems no slave log files.") system(paste("tail -",nlines," ", logfile,sep="")) } mpi.apply <- function(X, FUN, ..., comm=1){ n <- length(X) nslaves <- mpi.comm.size(comm)-1 if (nslaves < n) stop("data length must be at most total slave size") if (!is.function(FUN)) stop("FUN is not a function") length(list(...)) tag <- floor(runif(1,1,1000)) mpi.bcast.cmd(.mpi.worker.apply, n=n, tag=tag, comm=comm) mpi.bcast.Robj(list(FUN=FUN,dot.arg=list(...)),rank=0,comm=comm) if (n < nslaves) X=c(X,as.list(integer( nslaves-n))) mpi.scatter.Robj(c(list("master"),as.list(X)),root=0,comm=comm) out <- as.list(integer(n)) for (i in 1:n){ tmp<- mpi.recv.Robj(mpi.any.source(),tag,comm) src <- mpi.get.sourcetag()[1] out[[src]]<- tmp } out } .mpi.worker.apply <- function(n, tag){ .comm <- 1 tmpfunarg <- mpi.bcast.Robj(rank=0, comm=.comm) .tmpfun <- tmpfunarg$FUN dotarg <- tmpfunarg$dot.arg tmpdata.arg <- list(mpi.scatter.Robj(root=0,comm=.comm)) if (mpi.comm.rank(.comm) <= n){ out <- try(do.call(".tmpfun", c(tmpdata.arg, dotarg)),TRUE) mpi.send.Robj(out,0,tag,.comm) } } mpi.iapply <- function(X, FUN, ..., comm=1, sleep=0.01){ n <- length(X) nslaves <- mpi.comm.size(comm)-1 if (nslaves < n) stop("data length must be at most total slave size") if (!is.function(FUN)) stop("FUN is not a function") length(list(...)) tag <- floor(runif(1,1,1000)) mpi.bcast.cmd(.mpi.worker.apply, n=n, tag=tag,comm=comm) mpi.bcast.Robj(list(FUN=FUN,dot.arg=list(...)),rank=0,comm=comm) if (n < nslaves) X=c(X,as.list(integer( nslaves-n))) mpi.scatter.Robj(c(list("master"),as.list(X)),root=0,comm=comm) out <- as.list(integer(n)) done=0 anysource=mpi.any.source() repeat { if (mpi.iprobe(anysource,tag,comm)){ srctag <- mpi.get.sourcetag() charlen <- mpi.get.count(type=4) tmp <- unserialize(mpi.recv(x = raw(charlen), type = 4, srctag[1], srctag[2], comm)) out[[srctag[1]]]<- tmp done=done+1 } if (done < n) Sys.sleep(sleep) else break } gc() out } mpi.parSim <- function(n=100,rand.gen=rnorm, rand.arg=NULL, statistic, nsim=100, run=1, slaveinfo=FALSE, sim.seq=NULL, simplify=TRUE, comm=1, ...){ sim.seq=NULL if (mpi.comm.size(comm) < 2) stop("It seems no slaves running.") if (!is.function(rand.gen)) stop("rand.gen is not a function") if (!is.function(statistic)) stop("statistic is not a function") if (!is.null(rand.arg)) if (!is.list(rand.arg)) stop("rand.arg is not a list") if (length(list(...))>0) deparse(list(...)) slave.num <- mpi.comm.size(comm)-1 if (!is.null(sim.seq)) if (!is.integer(sim.seq)) stop("sim.seq is not an integer vector") else if (min(sim.seq)<1 && max(sim.seq)>slave.num && length(sim.seq)!=slave.num*run) stop("sim.seq is not in right order") mpi.bcast.cmd(.mpi.worker.sim, n=n, nsim=nsim, run=run, comm=comm) mpi.bcast.Robj(list(rand.gen=rand.gen, rand.arg=rand.arg, stat=statistic, stat.arg=list(...)), comm=comm) result <- as.list(integer(slave.num*run)) if (!is.null(sim.seq)){ for ( i in 1:(slave.num*run)){ result[[i]] <- mpi.recv.Robj(source=sim.seq[i], tag=8, comm=comm) mpi.send(as.integer(i), type=1, dest=sim.seq[i], tag=88, comm=comm) } return(.simplify(slave.num*run, result, simplify, nsim)) } i <- 0 anysrc <- mpi.any.source() anytag <- mpi.any.tag() mpi.parSim.tmp <- integer(slave.num*run) while (i < slave.num*run){ i <- i+1 result[[i]] <- mpi.recv.Robj(source=anysrc, tag=8, comm=comm) src <- mpi.get.sourcetag()[1] mpi.send(as.integer(i), type=1, dest=src, tag=88, comm=comm) mpi.parSim.tmp[i] <- src } if (slaveinfo){ slavename <- paste("slave",1:slave.num, sep="") cat("Finished slave jobs summary:\n") for (i in 1:slave.num){ if (i < 10) cat(slavename[i], " finished",sum(mpi.parSim==i), "job(s)\n") else cat(slavename[i], "finished",sum(mpi.parSim==i), "job(s)\n") } } .simplify(slave.num*run, result, simplify, nsim) } .mpi.worker.sim <- function(n, nsim, run){ .comm <- 1 tmpdata <- mpi.bcast.Robj(comm=.comm) rand.arg <- tmpdata$rand.arg stat.arg <- tmpdata$stat.arg .tmp.rand.gen <- tmpdata$rand.gen .tmp.statistic <- tmpdata$stat i <- 0 slave.num <- mpi.comm.size(.comm)-1 while( i < slave.num*(run-1)+1){ out <- replicate(nsim, do.call(".tmp.statistic", c(list(do.call(".tmp.rand.gen", c(list(n),rand.arg))), stat.arg))) mpi.send.Robj(obj=out, dest=0, tag=8, comm=.comm) i <- mpi.recv(integer(1), type=1, source=0, tag=88, comm=.comm) } } .docall <- function(fun, args) { if ((is.character(fun) && length(fun) == 1) || is.name(fun)) fun <- get(as.character(fun), envir = .GlobalEnv, mode = "function") enquote <- function(x) as.call(list(as.name("quote"), x)) do.call("fun", lapply(args, enquote)) } .splitIndices <- function(nx, ncl) { x <- 1:nx r <- nx/ncl ii <- 0:(ncl - 1) * r if (nx < ncl) intv <- 0:ncl else intv <- c(x[round(1 + ii)]-1,nx) structure(split(x, cut(x, intv)), names = NULL) } mpi.parMM <- function(A, B, job.num=mpi.comm.size(comm)-1, comm=1){ splitRows <- function(x, ncl) lapply(.splitIndices(nrow(x), ncl), function(i) x[i,, drop=FALSE]) .docall(rbind, mpi.applyLB(splitRows(A, job.num), get("%*%"), B, comm=comm)) } mpi.iparMM <- function(A, B, comm=1, sleep=0.01){ splitRows <- function(x, ncl) lapply(.splitIndices(nrow(x), ncl), function(i) x[i,, drop=FALSE]) .docall(rbind, mpi.iapply(splitRows(A, mpi.comm.size(comm)-1), get("%*%"), B, comm=comm, sleep=sleep)) } mpi.applyLB <- function(X, FUN, ..., apply.seq=NULL, comm=1){ apply.seq=NULL n <- length(X) slave.num <- mpi.comm.size(comm)-1 if (slave.num < 1) stop("There are no slaves running") if (n <= slave.num) { if (exists(".mpi.applyLB")) rm(".mpi.applyLB", envir=.GlobalEnv) return (mpi.apply(X,FUN,...,comm=comm)) } if (!is.function(FUN)) stop("FUN is not a function") length(list(...)) if (!is.null(apply.seq)) if (!is.integer(apply.seq)) stop("apply.seq is not an integer vector") else if (min(apply.seq)<1 && max(apply.seq)>slave.num && length(apply.seq)!=n) stop("apply.seq is not in right order") mpi.bcast.cmd(.mpi.worker.applyLB, n=n, comm=comm) mpi.bcast.Robj(list(FUN=FUN,dot.arg=list(...)),rank=0,comm=comm) out <- as.list(integer(n)) mpi.anysource <- mpi.any.source() mpi.anytag <- mpi.any.tag() for (i in 1:slave.num) mpi.send.Robj(list(data.arg=list(X[[i]])), dest=i,tag=i, comm=comm) if (!is.null(apply.seq)){ for ( i in 1:n){ tmp <- mpi.recv.Robj(source=apply.seq[i], tag=mpi.anytag, comm=comm) tag <- mpi.get.sourcetag()[2] out[[tag]]<- tmp j <- i+slave.num if (j <= n) mpi.send.Robj(list(data.arg=list(X[[j]])), dest=apply.seq[i],tag=j, comm=comm) else mpi.send.Robj(list(data.arg=list(n)),dest=apply.seq[i],tag=j,comm=comm) } return(out) } mpi.seq.tmp <- integer(n) for (i in 1:n){ tmp<- mpi.recv.Robj(mpi.anysource,mpi.anytag,comm) srctag <- mpi.get.sourcetag() out[[srctag[2]]]<- tmp mpi.seq.tmp[i] <- srctag[1] j <- i+slave.num if (j <= n) mpi.send.Robj(list(data.arg=list(X[[j]])), dest=srctag[1],tag=j, comm=comm) else mpi.send.Robj(list(data.arg=list(n)),dest=srctag[1],tag=j,comm=comm) } out } .mpi.worker.applyLB <- function(n){ .comm <- 1 tmpfunarg <- mpi.bcast.Robj(rank=0, comm=.comm) .tmpfun <- tmpfunarg$FUN dotarg <- tmpfunarg$dot.arg mpi.anytag <- mpi.any.tag() repeat { tmpdata.arg <- mpi.recv.Robj(source=0,tag=mpi.anytag, comm=.comm)$data.arg tag <- mpi.get.sourcetag()[2] if (tag > n) break out <- try(do.call(".tmpfun", c(tmpdata.arg, dotarg)),TRUE) mpi.send.Robj(out,0,tag,.comm) } } mpi.iapplyLB <- function(X, FUN, ..., apply.seq=NULL, comm=1, sleep=0.01){ apply.seq=NULL n <- length(X) slave.num <- mpi.comm.size(comm)-1 if (slave.num < 1) stop("There are no slaves running") if (n <= slave.num) { if (exists(".mpi.applyLB")) rm(".mpi.applyLB", envir =.GlobalEnv) return (mpi.iapply(X,FUN,...,comm=comm,sleep=sleep)) } if (!is.function(FUN)) stop("FUN is not a function") if (slave.num > 2000) stop("Total slaves are more than nonblock send/receive can handle") length(list(...)) if (!is.null(apply.seq)) if (!is.integer(apply.seq)) stop("apply.seq is not an integer vector") else if (min(apply.seq)<1 && max(apply.seq)>slave.num && length(apply.seq)!=n) stop("apply.seq is not in right order") mpi.bcast.cmd(.mpi.worker.applyLB, n=n, comm=comm) mpi.bcast.Robj(list(FUN=FUN,dot.arg=list(...)),rank=0,comm=comm) out <- as.list(integer(n)) mpi.anysource <- mpi.any.source() mpi.anytag <- mpi.any.tag() for (i in 1:slave.num) mpi.send.Robj(list(data.arg=list(X[[i]])), dest=i,tag=i,comm=comm) if (!is.null(apply.seq)){ i=0 repeat { if (mpi.iprobe(apply.seq[i+1],mpi.anytag,comm)){ i=i+1 j <- i+slave.num if ( j <= n) mpi.send.Robj(list(data.arg=list(X[[j]])), dest=apply.seq[i],tag=j, comm=comm) else mpi.send.Robj(as.integer(0),dest=apply.seq[i],tag=j,comm=comm) charlen <- mpi.get.count(type=4) tag <- mpi.get.sourcetag()[2] tmp <- unserialize(mpi.recv(x = raw(charlen), type = 4, apply.seq[i], tag, comm)) out[[tag]]<- tmp } if (i < n) Sys.sleep(sleep) else break } return(out) } mpi.seq.tmp <- integer(n) i=0 repeat { if (mpi.iprobe(mpi.anysource,mpi.anytag,comm)){ i=i+1 srctag <- mpi.get.sourcetag() src <- srctag[1] tag <- srctag[2] j <- i+slave.num if ( j <= n) mpi.send.Robj(list(data.arg=list(X[[j]])), dest=src,tag=j, comm=comm) else mpi.send.Robj(as.integer(0),dest=src,tag=j,comm=comm) charlen <- mpi.get.count(type=4) tmp <- unserialize(mpi.recv(x = raw(charlen), type = 4, src, tag, comm)) out[[tag]]<- tmp mpi.seq.tmp[i] <- src } if (i < n) Sys.sleep(sleep) else break } gc() out } .simplify <- function(n, answer, simplify, len=1, recursive=FALSE){ if (simplify && length(answer)&&length(common.len <- unique(unlist(lapply(answer, length)))) == 1 ) { if (common.len == len) unlist(answer, recursive = recursive) else if (common.len > len) array(unlist(answer, recursive = recursive), dim = c(common.len/len, n*len), dimnames = list(names(answer[[1]]), names(answer))) else answer } else answer } mpi.parLapply <- function(X, FUN, ..., job.num=mpi.comm.size(comm)-1, apply.seq=NULL, comm=1){ if (job.num < 2) stop("job.num is at least 2.") splitList <- function(x, ncl) lapply(.splitIndices(length(X), ncl), function(i) X[i]) .docall(c, mpi.applyLB(splitList(X, job.num), lapply, FUN, ..., apply.seq=apply.seq, comm=comm)) } mpi.iparLapply <- function(X, FUN, ..., job.num=mpi.comm.size(comm)-1, apply.seq=NULL, comm=1, sleep=0.01){ if (job.num < 2) stop("job.num is at least 2.") splitList <- function(X, ncl) lapply(.splitIndices(length(X), ncl), function(i) X[i]) .docall(c, mpi.iapplyLB(splitList(X, job.num), lapply, FUN, ..., apply.seq=apply.seq, comm=comm, sleep=sleep)) } mpi.parSapply <- function (X, FUN, ..., job.num=mpi.comm.size(comm)-1, apply.seq=NULL, simplify = TRUE, USE.NAMES = TRUE, comm=1) { FUN <- match.fun(FUN) answer <- mpi.parLapply(as.list(X),FUN,...,job.num=job.num,apply.seq=apply.seq,comm=comm) if (USE.NAMES && is.character(X) && is.null(names(answer))) names(answer) <- X .simplify(length(X),answer, simplify) } mpi.iparSapply <- function (X, FUN, ..., job.num=mpi.comm.size(comm)-1, apply.seq=NULL, simplify = TRUE, USE.NAMES = TRUE, comm=1,sleep=0.01) { FUN <- match.fun(FUN) answer <- mpi.iparLapply(as.list(X),FUN,...,job.num=job.num,apply.seq=apply.seq,comm=comm,sleep=sleep) if (USE.NAMES && is.character(X) && is.null(names(answer))) names(answer) <- X .simplify(length(X),answer, simplify) } mpi.parReplicate <- function(n, expr, job.num=mpi.comm.size(comm)-1, apply.seq=NULL, simplify = TRUE, comm=1){ mpi.parSapply(integer(n), eval.parent(substitute(function(...) expr)), job.num=job.num, apply.seq=apply.seq, simplify = simplify, comm=comm) } mpi.iparReplicate <- function(n, expr, job.num=mpi.comm.size(comm)-1, apply.seq=NULL, simplify = TRUE, comm=1,sleep=0.01){ mpi.iparSapply(integer(n), eval.parent(substitute(function(...) expr)), job.num=job.num, apply.seq=apply.seq, simplify = simplify, comm=comm,sleep=sleep) } mpi.parRapply <- function(X,FUN,...,job.num=mpi.comm.size(comm)-1,apply.seq=NULL,comm=1){ if (job.num < 2) stop("job.num is at least 2.") splitRows <- function(X, ncl) lapply(.splitIndices(nrow(X), ncl), function(i) X[i,, drop=FALSE]) .docall(c, mpi.applyLB(splitRows(X,job.num), apply, 1, FUN, ..., apply.seq=apply.seq, comm=comm)) } mpi.iparRapply <- function(X,FUN,...,job.num=mpi.comm.size(comm)-1,apply.seq=NULL,comm=1,sleep=0.01){ if (job.num < 2) stop("job.num is at least 2.") splitRows <- function(X, ncl) lapply(.splitIndices(nrow(X), ncl), function(i) X[i,, drop=FALSE]) .docall(c, mpi.iapplyLB(splitRows(X,job.num), apply, 1, FUN, ..., apply.seq=apply.seq, comm=comm,sleep=sleep)) } mpi.parCapply <- function(X,FUN,...,job.num=mpi.comm.size(comm)-1,apply.seq=NULL,comm=1){ if (job.num < 2) stop("job.num is at least 2.") splitCols <- function(X, ncl) lapply(.splitIndices(ncol(X), ncl), function(i) X[,i, drop=FALSE]) .docall(c, mpi.applyLB(splitCols(X,job.num), apply, 2, FUN, ..., apply.seq=apply.seq, comm=comm)) } mpi.iparCapply <- function(X,FUN,...,job.num=mpi.comm.size(comm)-1,apply.seq=NULL,comm=1,sleep=0.01){ if (job.num < 2) stop("job.num is at least 2.") splitCols <- function(X, ncl) lapply(.splitIndices(ncol(X), ncl), function(i) X[,i, drop=FALSE]) .docall(c, mpi.iapplyLB(splitCols(X,job.num), apply, 2, FUN, ..., apply.seq=apply.seq, comm=comm,sleep=sleep)) } mpi.parApply <- function(X, MARGIN, FUN, ..., job.num = mpi.comm.size(comm)-1, apply.seq=NULL, comm=1) { FUN <- match.fun(FUN) d <- dim(X) dl <- length(d) if(dl == 0) stop("dim(X) must have a positive length") ds <- 1:dl if(length(oldClass(X)) > 0) X <- if(dl == 2) as.matrix(X) else as.array(X) dn <- dimnames(X) s.call <- ds[-MARGIN] s.ans <- ds[MARGIN] d.call <- d[-MARGIN] d.ans <- d[MARGIN] dn.call<- dn[-MARGIN] dn.ans <- dn[MARGIN] d2 <- prod(d.ans) if(d2 == 0) { newX <- array(vector(typeof(X), 1), dim = c(prod(d.call), 1)) ans <- FUN(if(length(d.call) < 2) newX[,1] else array(newX[,1], d.call, dn.call), ...) return(if(is.null(ans)) ans else if(length(d.call) < 2) ans[1][-1] else array(ans, d.ans, dn.ans)) } newX <- aperm(X, c(s.call, s.ans)) dim(newX) <- c(prod(d.call), d2) if(length(d.call) < 2) { if (length(dn.call)) dimnames(newX) <- c(dn.call, list(NULL)) ans <- mpi.parLapply(1:d2, function(i, ...) FUN(newX[,i], ...), ..., job.num = job.num, apply.seq=apply.seq, comm=comm ) } else ans <- mpi.parLapply(1:d2, function(i, ...) FUN(array(newX[,i], d.call, dn.call), ...), ..., job.num = job.num, apply.seq=apply.seq, comm=comm) ans.list <- is.recursive(ans[[1]]) l.ans <- length(ans[[1]]) ans.names <- names(ans[[1]]) if(!ans.list) ans.list <- any(unlist(lapply(ans, length)) != l.ans) if(!ans.list && length(ans.names)) { all.same <- sapply(ans, function(X) identical(names(X), ans.names)) if (!all(all.same)) ans.names <- NULL } len.a <- if(ans.list) d2 else length(ans <- unlist(ans, recursive = FALSE)) if(length(MARGIN) == 1 && len.a == d2) { names(ans) <- if(length(dn.ans[[1]])) dn.ans[[1]] return(ans) } if(len.a == d2) return(array(ans, d.ans, dn.ans)) if(len.a > 0 && len.a %% d2 == 0) return(array(ans, c(len.a %/% d2, d.ans), if(is.null(dn.ans)) { if(!is.null(ans.names)) list(ans.names,NULL) } else c(list(ans.names), dn.ans))) return(ans) } mpi.iparApply <- function(X, MARGIN, FUN, ..., job.num = mpi.comm.size(comm)-1, apply.seq=NULL, comm=1,sleep=0.01) { FUN <- match.fun(FUN) d <- dim(X) dl <- length(d) if(dl == 0) stop("dim(X) must have a positive length") ds <- 1:dl if(length(oldClass(X)) > 0) X <- if(dl == 2) as.matrix(X) else as.array(X) dn <- dimnames(X) s.call <- ds[-MARGIN] s.ans <- ds[MARGIN] d.call <- d[-MARGIN] d.ans <- d[MARGIN] dn.call<- dn[-MARGIN] dn.ans <- dn[MARGIN] d2 <- prod(d.ans) if(d2 == 0) { newX <- array(vector(typeof(X), 1), dim = c(prod(d.call), 1)) ans <- FUN(if(length(d.call) < 2) newX[,1] else array(newX[,1], d.call, dn.call), ...) return(if(is.null(ans)) ans else if(length(d.call) < 2) ans[1][-1] else array(ans, d.ans, dn.ans)) } newX <- aperm(X, c(s.call, s.ans)) dim(newX) <- c(prod(d.call), d2) if(length(d.call) < 2) { if (length(dn.call)) dimnames(newX) <- c(dn.call, list(NULL)) ans <- mpi.iparLapply(1:d2, function(i, ...) FUN(newX[,i], ...), ..., job.num = job.num, apply.seq=apply.seq, comm=comm, sleep=sleep ) } else ans <- mpi.iparLapply(1:d2, function(i, ...) FUN(array(newX[,i], d.call, dn.call), ...), ..., job.num = job.num, apply.seq=apply.seq, comm=comm, sleep=sleep) ans.list <- is.recursive(ans[[1]]) l.ans <- length(ans[[1]]) ans.names <- names(ans[[1]]) if(!ans.list) ans.list <- any(unlist(lapply(ans, length)) != l.ans) if(!ans.list && length(ans.names)) { all.same <- sapply(ans, function(X) identical(names(X), ans.names)) if (!all(all.same)) ans.names <- NULL } len.a <- if(ans.list) d2 else length(ans <- unlist(ans, recursive = FALSE)) if(length(MARGIN) == 1 && len.a == d2) { names(ans) <- if(length(dn.ans[[1]])) dn.ans[[1]] return(ans) } if(len.a == d2) return(array(ans, d.ans, dn.ans)) if(len.a > 0 && len.a %% d2 == 0) return(array(ans, c(len.a %/% d2, d.ans), if(is.null(dn.ans)) { if(!is.null(ans.names)) list(ans.names,NULL) } else c(list(ans.names), dn.ans))) return(ans) }
blimMD <- function(K, N.R, R = as.binmat(N.R), errtype = c("both", "error", "guessing"), incrule = c("minimum", "hypblc1", "hypblc2"), m = 1){ K <- as.matrix(K) N.R <- setNames(as.integer(N.R), names(N.R)) N <- sum(N.R) nitems <- ncol(K) npat <- nrow(R) nstates <- nrow(K) d.RK <- switch(match.arg(errtype), both = apply(K, 1, function(k) colSums(xor(t(R), k))), error = apply(K, 1, function(k) colSums(ifelse(k - t(R) < 0, NA, k - t(R)))), guessing = apply(K, 1, function(k) colSums(ifelse(t(R) - k < 0, NA, t(R) - k))) ) d.min <- apply(d.RK, 1, min, na.rm=TRUE) i.RK <- switch(match.arg(incrule), minimum = (d.RK == d.min) & !is.na(d.RK), hypblc1 = replace(1/(1 + d.RK - d.min)^m, is.na(d.RK), 0), hypblc2 = replace(1/(1 + d.RK)^m, is.na(d.RK), 0)) m.RK <- i.RK/rowSums(i.RK) * N.R disc.tab <- xtabs(N.R ~ d.min) disc <- as.numeric(names(disc.tab)) %*% disc.tab / N P.K <- colSums(m.RK)/N names(P.K) <- if(is.null(rownames(K))) as.pattern(K) else rownames(K) beta <- eta <- numeric(nitems) names(beta) <- names(eta) <- if(is.null(colnames(K))){ make.unique(c("a", letters[(seq_len(nitems) %% 26) + 1])[-(nitems + 1)], sep="") }else colnames(K) for(j in seq_len(nitems)){ beta[j] <- sum(m.RK[which(R[,j] == 0), which(K[,j] == 1)]) / sum(m.RK[,which(K[,j] == 1)]) eta[j] <- sum(m.RK[which(R[,j] == 1), which(K[,j] == 0)]) / sum(m.RK[,which(K[,j] == 0)]) } beta[is.na(beta)] <- 0 eta[is.na( eta)] <- 0 z <- list(discrepancy=c(disc), P.K=P.K, beta=beta, eta=eta, disc.tab=disc.tab, nstates=nstates, npatterns=npat, ntotal=N, nerror=NA, method="MD", iter=NA, loglik=NA) class(z) <- "blim" z }
AVif <- function(IFriv) { n <- ncol(IFriv) A <- apply(IFriv, 2, tcrossprod) dim(A) <- c(nrow(IFriv), nrow(IFriv), n) A.AV <- apply(A, 1:2, mean)/n dimnames(A.AV) <- list(rownames(IFriv), rownames(IFriv)) A.AV }
x <- 1:10 x <- rlang::set_names(x, letters[1:10]) x_array <- as.array(x) x_mat <- as.matrix(x) context("test-coercion-matrix") test_that("Can coerce to matrices from various inputs", { expect_is(as_matrix(x), "matrix") expect_is(as_matrix(x_array), "matrix") expect_is(as_matrix(x_mat), "matrix") }) test_that("vector -> matrix makes a 1 column matrix", { expect_equal(rray_dim(as_matrix(x)), c(vec_size(x), 1L)) }) test_that("names() and rray_dim_names() are kept", { nms <- c(rray_dim_names(x), rray_empty_dim_names(1)) expect_equal(rray_dim_names(as_matrix(x)), nms) expect_equal(rray_dim_names(as_matrix(x_array)), nms) expect_equal(rray_dim_names(as_matrix(x_mat)), nms) }) test_that("meta dim names are kept", { x_nms <- rray_dim_names(x_array) names(x_nms) <- "meta_nm" x_array_meta <- x_array rray_dim_names(x_array_meta) <- x_nms nms_with_meta <- c(rray_dim_names(x_array_meta), rray_empty_dim_names(1)) expect_equal( rray_dim_names(as_matrix(x_array_meta)), nms_with_meta ) }) test_that("Cannot reduce >2D to a matrix most of the time", { expect_error(as_matrix(rray(1, c(1, 1, 2))), "A >2D object") expect_equal( as_matrix(rray(1, c(2, 3, 1))), new_matrix(1, c(2, 3)) ) }) context("test-coercion-array") test_that("Can coerce to arrays from various inputs", { expect_is(as_array(x), "array") expect_is(as_array(x_array), "array") expect_is(as_array(x_mat), "matrix") }) test_that("vector -> array makes a 1D array", { expect_equal(rray_dim(as_array(x)), vec_size(x)) }) test_that("names() and rray_dim_names() are kept", { nms_1D <- rray_dim_names(x) nms_2D <- c(rray_dim_names(x), rray_empty_dim_names(1)) expect_equal(rray_dim_names(as_array(x)), nms_1D) expect_equal(rray_dim_names(as_array(x_array)), nms_1D) expect_equal(rray_dim_names(as_array(x_mat)), nms_2D) }) test_that("meta dim names are kept", { x_rray <- as_rray(x_array) x_nms <- rray_dim_names(x_rray) names(x_nms) <- "meta_nm" rray_dim_names(x_rray) <- x_nms nms_with_meta <- rray_dim_names(x_rray) expect_equal( rray_dim_names(as_array(x_rray)), nms_with_meta ) }) context("test-coercion-rray") test_that("Can coerce to rrays from various inputs", { expect_is(as_rray(x), "vctrs_rray") expect_is(as_rray(x_array), "vctrs_rray") expect_is(as_rray(x_mat), "vctrs_rray") }) test_that("vector -> rray makes a 1D rray", { expect_equal(rray_dim(as_rray(x)), vec_size(x)) }) test_that("names() and rray_dim_names() are kept", { nms_1D <- rray_dim_names(x) nms_2D <- c(rray_dim_names(x), rray_empty_dim_names(1)) expect_equal(rray_dim_names(as_rray(x)), nms_1D) expect_equal(rray_dim_names(as_rray(x_array)), nms_1D) expect_equal(rray_dim_names(as_rray(x_mat)), nms_2D) }) test_that("meta dim names are kept", { x_nms <- rray_dim_names(x_array) names(x_nms) <- "meta_nm" x_array_meta <- x_array rray_dim_names(x_array_meta) <- x_nms nms_with_meta <- rray_dim_names(x_array_meta) expect_equal( rray_dim_names(as_rray(x_array_meta)), nms_with_meta ) }) test_that("4D tests", { x_4D <- array(1, c(1, 1, 1, 1), dimnames = list("r1", "c1", "..3_1", "..4_1")) nms_4D <- rray_dim_names(x_4D) expect_equal(rray_dim(as_rray(x_4D)), c(1, 1, 1, 1)) expect_equal(rray_dim_names(as_rray(x_4D)), nms_4D) })
ceresPlots <- function(model, ...){ UseMethod("ceresPlots") } ceresPlots.default<-function(model, terms= ~ ., layout=NULL, ask, main, ...){ terms <- if(is.character(terms)) paste("~", terms) else terms vform <- update(formula(model), terms) if(any(is.na(match(all.vars(vform), all.vars(formula(model)))))) stop("Only predictors in the formula can be plotted.") mf <- attr(model.frame(model), "terms") terms <- attr(mf, "term.labels") vterms <- attr(terms(vform), "term.labels") good <- NULL if (any(attr(terms(model),"order")>1)) { stop("CERES plots not available for models with interactions.")} for (term in vterms) if( inherits(model$model[[term]], "numeric") | inherits(model$model[[term]], "integer")) good <- c(good,term) nt <- length(good) if(length(good) < length(vterms)) warning("Factors skipped in drawing CERES plots.") vterms <- good if (nt == 0) stop("No plots specified") if (missing(main)) main <- if (nt == 1) "CERES Plot" else "CERES Plots" if (nt == 0) stop("No plots specified") if (nt > 1 & (is.null(layout) || is.numeric(layout))) { if(is.null(layout)){ layout <- switch(min(nt, 9), c(1, 1), c(1, 2), c(2, 2), c(2, 2), c(3, 2), c(3, 2), c(3, 3), c(3, 3), c(3, 3)) } ask <- if(missing(ask) || is.null(ask)) prod(layout)<nt else ask op <- par(mfrow=layout, ask=ask, no.readonly=TRUE, oma=c(0, 0, 1.5, 0), mar=c(5, 4, 1, 2) + .1) on.exit(par(op)) } if(!is.null(class(model$na.action)) && inherits(model$na.action, 'exclude')) class(model$na.action) <- 'omit' for(term in vterms) ceresPlot(model, term, main="", ...) mtext(side=3, outer=TRUE, main, cex=1.2) invisible(0) } ceresPlot<-function (model, ...) { UseMethod("ceresPlot") } ceresPlot.lm<-function(model, variable, id=FALSE, line=TRUE, smooth=TRUE, col=carPalette()[1], col.lines=carPalette()[-1], xlab, ylab, pch=1, lwd=2, grid=TRUE, ...){ id <- applyDefaults(id, defaults=list(method=list(abs(residuals(model, type="pearson")), "x"), n=2, cex=1, col=carPalette()[1], location="lr"), type="id") if (isFALSE(id)){ id.n <- 0 id.method <- "none" labels <- id.cex <- id.col <- id.location <- NULL } else{ labels <- id$labels if (is.null(labels)) labels <- names(na.omit(residuals(model))) id.method <- id$method id.n <- if ("identify" %in% id.method) Inf else id$n id.cex <- id$cex id.col <- id$col id.location <- id$location } smoother.args <- applyDefaults(smooth, defaults=list(smoother=loessLine, var=FALSE), type="smooth") if (!isFALSE(smoother.args)) { smoother <- smoother.args$smoother smoother.args$smoother <- NULL if (is.null(smoother.args$spread)) smoother.args$spread <- smoother.args$var } else smoother <- "none" expand.model.frame <- function (model, extras, envir = environment(formula(model)), na.expand = FALSE){ f <- formula(model) data <- eval(model$call$data, envir) ff <- foo ~ bar + baz if (is.call(extras)) gg <- extras else gg <- parse(text = paste("~", paste(extras, collapse = "+")))[[1]] ff[[2]] <- f[[2]] ff[[3]][[2]] <- f[[3]] ff[[3]][[3]] <- gg[[2]] if (!na.expand) { naa <- model$call$na.action subset <- model$call$subset rval <- if (is.null(data)){ eval(call("model.frame", ff, data=model.frame(model), subset = subset, na.action = naa), envir)} else eval(call("model.frame", ff, data = data, subset = subset, na.action = naa), envir) } else { subset <- model$call$subset rval <- eval(call("model.frame", ff, data = data, subset = subset, na.action = I), envir) oldmf <- model.frame(model) keep <- match(rownames(oldmf), rownames(rval)) rval <- rval[keep, ] class(rval) <- "data.frame" } return(rval) } if(!is.null(class(model$na.action)) && inherits(model$na.action, 'exclude')) class(model$na.action) <- 'omit' var<-if (is.character(variable) & 1==length(variable)) variable else deparse(substitute(variable)) mod.mat<-model.matrix(model) obs<-names(residuals(model)) all.obs<-if (is.null(model$call$data)) obs else row.names(eval(model$call$data)) xx<-rep(NA, length(all.obs)) names(xx)<-all.obs terms<-predictor.names(model) if (is.na(match(var, terms))) stop(paste(var,"is not in the model.")) if (!is.null(model$contrasts[[var]])) stop(paste(var,"is a factor.")) terms<-terms[-match(var,terms)] if (any(attr(terms(model),"order")>1)) { stop("ceres plot not available for models with interactions.") } .x<-xvars<-NULL for (xvar in terms){ if (is.null(model$contrasts[[xvar]])){ xvars<-c(xvars,xvar) xx[obs]<-fitted.values(loess(as.formula(paste("mod.mat[,'",xvar,"']~mod.mat[,'",var,"']",sep="")))) .x<-cbind(.x, xx) } } if (is.null(xvars)) stop("There are no covariates.") n.x<-length(xvars) mf<-na.omit(expand.model.frame(model, all.vars(formula(model)))) rownames(.x)<-all.obs mf$.x<-.x[obs,] aug.model <- update(model, . ~ . + .x, data=mf, subset=NULL) aug.mod.mat<-model.matrix(aug.model) coef<-coefficients(aug.model) k<-length(coef) posn<-k:(k-n.x+1) partial.res<-residuals(aug.model, "partial")[,var] + aug.mod.mat[,posn] %*% as.matrix(coef[posn]) xlab <- if(!missing(xlab)) xlab else var ylab <- if(!missing(ylab)) ylab else paste("CERES Residual(",responseName(model),")", sep="") plot(mod.mat[,var], partial.res, xlab=xlab, col=col, pch=pch, ylab=ylab, type="n", ...) if(grid){ grid(lty=1, equilogs=FALSE) box()} points(mod.mat[,var], partial.res, col=col, pch=pch) showLabels(mod.mat[,var], partial.res, labels=labels, method=id.method, n=id.n, cex=id.cex, col=id.col, location=id.location) if (line) abline(lm(partial.res~mod.mat[,var]), lty=2, lwd=lwd, col=col.lines[1]) if (is.function(smoother)) { smoother(mod.mat[, var], partial.res, col=col.lines[2], log.x=FALSE, log.y=FALSE, spread=smoother.args$spread, smoother.args=smoother.args) } } ceresPlot.glm<-function(model, ...){ ceresPlot.lm(model, ...) }
postTest <- function(object.list) { if(!is(object.list, "haplinStrat")) stop("Argument 'object.list' should be the result from running 'haplinStrat'", call. = F) if(any(is.na(object.list))) { warning("NA element in list of estimation results. Interaction test not performed", call. = F) return(object.list) } .object.list <- object.list[-1] if(length(.object.list) <= 1) stop("Need at least two strata", call. = F) .stratnavn <- names(.object.list) if(is.null(.stratnavn)) .stratnavn <- as.character(seq(along = .object.list)) .info <- lapply(.object.list, function(x) x$info) .response <- .info[[1]]$haplos$response .maternal <- .info[[1]]$model$maternal .poo <- .info[[1]]$model$poo .tmp.selected.haplotypes <- lapply(.info, function(x)x$haplos$selected.haplotypes) .sel.haps <- .tmp.selected.haplotypes[[1]] .sjekk <- sapply(.tmp.selected.haplotypes[-1], function(x) identical(tolower(x), tolower(.sel.haps))) if(any(!.sjekk)) stop("Different haplotypes selected in different strata!", call. = F) .tmp.ref.cat <- lapply(.info, function(x){ .tmp <- x$haplos$ref.cat names(.tmp) <- tolower(names(.tmp)) }) .ref.cat <- .tmp.ref.cat[[1]] .sjekk <- sapply(.tmp.ref.cat[-1], function(x) identical(x, .ref.cat)) if(any(!.sjekk)) stop("Cannot do interaction test with different reference categories", call. = F) .params <- lapply(.object.list, coef) .coef <- lapply(.params, function(x) x$coef) .cov <- lapply(.params, function(x) x$cov) .tmp <- f.post.diff(coeff = .coef, covar = .cov) if(.poo) .tmp <- f.post.poo.diff(coeff = .tmp$coef, covar = .tmp$cov) .coef <- .tmp$coeff .cov <- .tmp$cov .names <- rownames(.coef[[1]]) .effs <- f.coefnames(.names) .names.tests <- list(haplo.freq = .effs$haplo.freq, child = c(.effs$child.s, .effs$child.d), child.poo = c(.effs$child.poo.m, .effs$child.poo.f, .effs$child.d), poo = .effs$poo, maternal = c(.effs$maternal.s, .effs$maternal.d)) if(.poo){ if(.maternal){ .test <- c("haplo.freq", "child.poo", "poo", "maternal") }else{ .test <- c("haplo.freq", "child.poo", "poo") } } else { if(.maternal){ .test <- c("haplo.freq", "child", "maternal") }else{ .test <- c("haplo.freq", "child") } } standard.tests <- F if(standard.tests){ .c <- .cdd <- NULL .f.extr <- function(co, selpars){ if(ncol(co[[1]]) == 1){ .res <- lapply(co, function(x) x[selpars, , drop = F]) }else { .res <- lapply(co, function(x) x[selpars, selpars, drop = F]) } return(.res) } .coef.c <- .f.extr(.coef, .c) if(.response == "free") .coef.cdd <- .f.extr(.coef, .cdd) .coef.comb <- .f.extr(.coef, c(.c, .cdd)) .cov.c <- .f.extr(.cov, .c) if(.response == "free") .cov.cdd <- .f.extr(.cov, .cdd) .cov.comb <- .f.extr(.cov, c(.c, .cdd)) .contr.c <- diag(length(.coef.c[[1]])) if(.response == "free") .contr.cdd <- diag(length(.coef.cdd[[1]])) .contr.comb <- diag(length(.coef.comb[[1]])) .res.c <- vector(length(.coef.c), mode = "list") if(.response == "free") .res.cdd <- vector(length(.coef.cdd), mode = "list") .res.comb <- vector(length(.coef.comb), mode = "list") for (i in seq(along = .coef.c)){ .res.c[[i]] <- f.post.chisq(coeff = .coef.c[[i]], covar = .cov.c[[i]], contrast.mat = .contr.c) if(.response == "free") .res.cdd[[i]] <- f.post.chisq(coeff = .coef.cdd[[i]], covar = .cov.cdd[[i]], contrast.mat = .contr.cdd) .res.comb[[i]] <- f.post.chisq(coeff = .coef.comb[[i]], covar = .cov.comb[[i]], contrast.mat = .contr.comb) f.vis(.res.c, vis = F) if(.response == "free") f.vis(.res.cdd, vis = F) } cat("\nIndividual Wald tests within each stratum, \nfor single dose, double dose and combined:\n") cat("\nPost-hoc (Wald) test single dose:") .res.c.vis <- cbind("Stratum: ", format(.stratnavn, justify = "right"), ", Chi-squared = ", round(sapply(.res.c, function(x)x$chisq), 3), ", df's = ", sapply(.res.c, function(x) x$df), ", p-value = ", round(sapply(.res.c, function(x) x$pval), 5)) dimnames(.res.c.vis) <- list(rep("", dim(.res.c.vis)[1]), rep("", dim(.res.c.vis)[2])) print(.res.c.vis, quote = F, print.gap = 0) if(.response == "free") { cat("\nPost-hoc (Wald) test double dose:") .res.cdd.vis <- cbind("Stratum: ", format(.stratnavn, justify = "right"), ", Chi-squared = ", round(sapply(.res.cdd, function(x)x$chisq), 3), ", df's = ", sapply(.res.cdd, function(x) x$df), ", p-value = ", round(sapply(.res.cdd, function(x) x$pval), 5)) dimnames(.res.cdd.vis) <- list(rep("", dim(.res.cdd.vis)[1]), rep("", dim(.res.cdd.vis)[2])) print(.res.cdd.vis, quote = F, print.gap = 0) } cat("\nPost-hoc (Wald) test combined single and double dose:") .res.comb.vis <- cbind("Stratum: ", format(.stratnavn, justify = "right"), ", Chi-squared = ", round(sapply(.res.comb, function(x)x$chisq), 3), ", df's = ", sapply(.res.comb, function(x) x$df), ", p-value = ", round(sapply(.res.comb, function(x) x$pval), 5)) dimnames(.res.comb.vis) <- list(rep("", dim(.res.comb.vis)[1]), rep("", dim(.res.comb.vis)[2])) print(.res.comb.vis, quote = F, print.gap = 0) cat("\nCompare combined to overall likelihood ratio p-values:") .p.value.overall <- sapply(.object.list, function(x){ .tmp <- summary(x)$loglike["p.value.overall"] if(is.null(.tmp)) .tmp <- NA return(.tmp) }) .p.value.overall.vis <- cbind("Stratum: ", format(.stratnavn, justify = "right"), ", p-value = ", round(as.numeric(.p.value.overall), 5)) dimnames(.p.value.overall.vis) <- list(rep("", nrow(.p.value.overall.vis)), rep("", ncol(.p.value.overall.vis))) print(.p.value.overall.vis, quote = F, print.gap = 0) } .chisq.res <- lapply(.test, function(x) f.posttest(coef_ = .coef, cov_ = .cov, test = .names.tests[[x]])) names(.chisq.res) <- .test .ut <- lapply(.chisq.res, function(x) { x$y <- NULL return(unlist(x)) }) .ut <- do.call("rbind", .ut) .ut <- dframe(test = rownames(.ut), .ut) rownames(.ut) <- NULL attr(.ut,"coef") <- .coef attr(.ut,"cov") <- .cov return(.ut) }
fMP_CorrGxM <- function(listdata, param, PointsW) { m = c(listdata$M1,listdata$M2); p1 = listdata$P1; p2 = listdata$P2; rG = listdata$rG; muM = param$muM; muP = param$muP; aM = param$aM; cM = param$cM; eM = param$eM; aP = param$aP; cP = param$cP; eP = param$eP; rA = param$rA; rC = param$rC; rE = param$rE; alphaP = param$alphaP; kappaP = param$kappaP; epsilonP = param$epsilonP; aC = rA*aP; cC = rC*cP; eC = rE*eP; aU = sqrt(1-rA^2)*aP; cU = sqrt(1-rC^2)*cP; eU = sqrt(1-rE^2)*eP; alphaC = rA*alphaP; alphaU = sqrt(1-rA^2)*alphaP; kappaC = rC*kappaP; kappaU = sqrt(1-rC^2)*kappaP; epsilonC = rE*epsilonP; epsilonU = sqrt(1-rE^2)*epsilonP; Points = PointsW$Points; W=PointsW$W; K3 = length(W); entry1 = aM^2 + cM^2 + eM^2; entry2 = aM^2*rG + cM^2; SigmaM = matrix(c(entry1, entry2, entry2, entry1),2,2); invSigmaM = solve(SigmaM); fm = log(2*pi) + 0.5*log(det(SigmaM)) + 0.5*(m-muM)%*%invSigmaM%*%(m-muM); SigmaAC = matrix(c( 1, rG, 0, rG, 1, 0, 0, 0, 1), 3,3) SigmaACM = matrix(c( aM, aM*rG, cM, aM*rG, aM, cM), 3,2) covAC_M = SigmaAC - SigmaACM %*%invSigmaM%*%t(SigmaACM); trans = sqrt(2)*t(chol(covAC_M)); tmpA = SigmaACM %*% invSigmaM; tmpB = tmpA %*% c(muM,muM); tmpC = tmpA %*% m - tmpB; tmpD = matrix(rep(tmpC,K3),3,K3) AC = tmpD + trans %*% Points; CC = t(matrix(rep(AC[3,],2),K3,2)) tmpA = matrix(rep(m-muM,K3),2,K3) E = (tmpA - aM*AC[1:2,] - cM*CC) / eM; muP_ACM = muP+(aC+alphaC*m)*AC[1:2,]+(cC+kappaC*m)*CC+(eC+epsilonC*m)*E; entry11 = (aU+alphaU*m[1])^2+(cU+kappaU*m[1])^2+(eU+epsilonU*m[1])^2; entry12 = (aU+alphaU*m[1])*(aU+alphaU*m[2])*rG+(cU+kappaU*m[1])*(cU+kappaU*m[2]); entry22 = (aU+alphaU*m[2])^2+(cU+kappaU*m[2])^2+(eU+epsilonU*m[2])^2; det_covP_ACM = entry11*entry22 - entry12^2; infind = det_covP_ACM < 1e-6; entry11[infind] = 1e-3; entry12[infind] = 0; entry22[infind] = 1e-3; tmpA = (p1-muP_ACM[1,])*entry22 - (p2-muP_ACM[2,])*entry12; tmpB = -(p1-muP_ACM[1,])*entry12 + (p2-muP_ACM[2,])*entry11; tmpC = (tmpA*(p1-muP_ACM[1,]) + tmpB*(p2-muP_ACM[2,])) / det_covP_ACM; inversevalue = 2*pi*sqrt(det_covP_ACM)*exp(0.5*tmpC); fp_M = -log(sum(W/inversevalue)) + 1.5*log(pi); return(fm+fp_M); }
autocol = function(x, set = '', alpha = NA, limits = NA, na_colour = NA, bias = 1, legend_len = 6){ pal_type = switch (class(x)[1], 'factor' = 'categorical', 'character' = 'categorical', 'logical' = 'categorical', 'integer' = 'continuous', 'numeric' = 'continuous', 'trynumeric' ) if(pal_type=='trynumeric'){ original_class = class(x) x = as.numeric(x) if(!length(x) > 1) stop('Could not convert as.numeric(x)') } x_na = is.na(x) if(pal_type=='categorical'){ set_palette = get_set(set, default = 'sasha') if(class(x)=='character') x = factor(x, levels=unique(x)) col_level = as.integer(as.factor(x)) %% length(set_palette) col_level[col_level==0] = length(set_palette) res_pal = set_palette[col_level] legend_labels = 1:length(unique(x)) %% length(set_palette) legend_labels[legend_labels==0] = length(set_palette) legend_fill = set_palette[legend_labels] legend_labels = as.character(unique(as.factor(x))) options(autolegend = list(legend_labels, legend_fill)) } if(pal_type=='continuous' | pal_type=='trynumeric'){ chosen_colour_ramp = colorRamp(get_set(set, default = 'viridis'), space = 'Lab', bias = bias) if(is.na(limits[1])) limits = range(x, na.rm = TRUE) create_autolegend_data(limits = limits, chosen_colour_ramp = chosen_colour_ramp, legend_len = legend_len, override_class = if(pal_type=='trynumeric') original_class else NA ) x_scaled = (x - limits[1]) / (limits[2] - limits[1]) x_scaled = pmin(1,pmax(0, x_scaled)) x_scaled[x_na] = 0 res_pal = rgb(chosen_colour_ramp(x_scaled), maxColorValue = 255) res_pal[x_na] = NA } res_pal[x_na] = na_colour if(!is.na(alpha[1])){ max_alpha = if(length(alpha)==1) 1 else max(alpha,na.rm=TRUE) alpha = pmax(0, alpha, na.rm=TRUE) res_pal = rgb(t(col2rgb( res_pal )), alpha=255*alpha/max_alpha, maxColorValue=255 ) } return(res_pal) } autolegend = function(...){ if(!'autolegend' %in% names(options())) stop('Must call autocol(...) first to create options("autolegend")') if('pch' %in% names(list(...))) legend(..., locator(n=1), legend = options('autolegend')[[1]][[1]], col = options('autolegend')[[1]][[2]], xpd = NA) else legend(..., locator(n=1), legend = options('autolegend')[[1]][[1]], fill = options('autolegend')[[1]][[2]], xpd = NA) return(NULL) } autopal = function(set = '', n = 30, limits = NA, bias = 1, legend_len = 6){ chosen_colour_ramp = colorRamp(get_set(set), space = 'Lab', bias = bias) if(!is.na(limits[1])){ original_class = NA if(!class(limits) %in% c('numeric','integer')){ original_class = class(limits) limits = as.numeric(limits)} create_autolegend_data(limits = limits, chosen_colour_ramp = chosen_colour_ramp, legend_len = legend_len, override_class = original_class) } palcols = rgb(chosen_colour_ramp(c(0,seq(0,1,length.out=n-2),1)), maxColorValue = 255) return(palcols) } create_autolegend_data = function(limits, chosen_colour_ramp, legend_len = 6, override_class = NA){ legend_labels = pretty(limits, n = legend_len) longest_label = max(nchar(as.character(legend_labels))) legend_labels[1] = signif(limits[1], digits = longest_label) legend_labels[length(legend_labels)] = signif(limits[2], digits = longest_label) legend_scaled = (legend_labels-min(legend_labels))/diff(range(legend_labels)) legend_fill = rgb(chosen_colour_ramp(legend_scaled), maxColorValue = 255) if(!is.na(override_class[1])) attr(legend_labels, 'class') = override_class options(autolegend = list(legend_labels, legend_fill)) }
source("ESEUR_config.r") patches=read.csv(paste0(ESEUR_dir, "regression/linux-patch-fix.csv.xz"), as.is=TRUE) cleaned=subset(patches, Total.Updates < 40) c_mod=glm(Fixes ~ Total.Updates, data=cleaned) print(summary(c_mod))
setMethod("show", "datagroup", function(object){ cat('An object of class "datagroup":\n') for (i in 1:length(object@group)){ cat(paste0('[',i,'] ')) cat(object@group[[i]]$title,'\n') cat(' url:',object@group[[i]]$url,'\n') } })
lastdaypresent <- function(x, ID = "all", refdate = NULL) { if (class(x) == "elo") { pm <- x$pmat } else { stop("so far 'x' must be of class 'elo'...", call. = FALSE) } if (is.null(refdate)) refdate <- max(x$truedates) pm <- pm[x$truedates <= refdate, ] if (0 %in% colSums(pm)) { pids <- names(pm)[colSums(pm) == 0] pm <- pm[, colSums(pm) > 0] } else { pids <- NA } res <- x$truedates[apply(pm, 2, function(z) max(which(z == 1)))] names(res) <- colnames(pm) if (!is.na(pids[1])) { res <- c(res, rep(NA, length(pids))) names(res) <- c(names(pm), pids) } if (ID != "all") { if (ID %in% names(res)) { res <- as.Date(as.character(res[ID])) } else { res <- NA warning("ID not found...", call. = FALSE) } } return(res) }
LW_er_lambdacov_none_effectcov_none_responsecov_none <- function(par, fitness, target, density, covariates, fixed_parameters){ num.sp <- nrow(target) pos <- 1 if(is.null(fixed_parameters[["lambda"]])){ lambda <- par[pos:(pos + num.sp - 1)] pos <- pos + num.sp }else{ lambda <- fixed_parameters[["lambda"]] } if(is.null(fixed_parameters[["effect"]])){ effect <- par[pos:(pos + num.sp - 1)] pos <- pos + num.sp }else{ effect <- fixed_parameters[["effect"]] } if(is.null(fixed_parameters[["response"]])){ response <- par[pos:(pos + num.sp - 1)] pos <- pos + num.sp }else{ response <- fixed_parameters[["response"]] } sigma <- par[length(par)] lambda.part <- colSums(lambda*target) r.part <- colSums(response*target) e.part <- colSums(density^effect) pred <- lambda.part/(1+(r.part*e.part)) llik <- dnorm(fitness, mean = (log(pred)), sd = (sigma), log=TRUE) return(sum(-1*llik)) }
read.wdat <- function(cmd, datfile = cmd$data, na = " ", ilabels = NULL) { dat <- readLines(datfile) ncols <- max(nchar(dat)) nvars <- cmd$ni + 1 if(!all(nchar(dat) == ncols)) warning("Lines", paste(which(nchar(dat) != ncols), collapse = ", "), "are missing information") dat <- format(dat) out <- data.frame(matrix(ncol = nvars, nrow = length(dat))) out[, 1] <- trim(substr(dat, cmd$name1, cmd$name1 + cmd$namelen - 1)) for(i in 1:cmd$ni) { out[, i + 1] <- substr(dat, cmd$item1 + i - 1, cmd$item1 + i - 1) out[out[, i + 1] == na, i + 1] <- NA out[, i + 1] <- as.numeric(out[, i + 1]) } if(!is.null(ilabels)) cmd$labels <- ilabels if(!is.null(cmd$labels)) names(out) <- c("name", cmd$labels) else names(out) <- c("name", paste("i", 1:cmd$ni, sep = "")) return(out) }
options(width=65, digits = 3) pkg <- search()[2] while (search()[2] != if(.Platform$GUI == "AQUA") "tools:RGUI" else "package:stats") { spkg <- strsplit( pkg, ":" )[[1]][2] if (packageHasNamespace(spkg, .libPaths()[1]) ) unloadNamespace(spkg ) else detach(pos = match(pkg, search())) pkg <- search()[2] } rm(list = ls()) gc() library(MPDiR) library(lattice) ltheme <- canonical.theme("pdf", color = FALSE) ltheme$strip.background$bg <- "grey85" lattice.options(default.theme = ltheme) formals(deparse)$width.cutoff <- 50L assignInNamespace("deparse", deparse, "base") rm(deparse) library(MPDiR) RespFun <- function(x, n) x^n x <- seq(0, 1, len = 200) xy <- expand.grid(x = x, y = x) xy$Diff <- with(xy, RespFun(x, 0.25) + RespFun(y, 1.75)) xp <- c(0.4, 0.6) yp <- c((1 - xp^0.25)^(1/1.75), (1.25 - xp^0.25)^(1/1.75)) print( contourplot(Diff ~ x * y, xy, at = c(1, 1.25), aspect = "iso", subscripts = TRUE, scale = list(x = list(at = xp, labels = expression(varphi^1, varphi*minute^1 )), y = list(at = yp, labels = expression(varphi^2, varphi*minute^2, varphi*minute*minute^2, varphi*minute*minute*minute^2) ), cex = 1.5 ), labels = FALSE, xlab = list(label = "Scale 1", cex = 1.3), ylab = list(label = "Scale 2", cex = 1.3), panel = function(x, y, z, subscripts,...){ panel.contourplot(x, y, z, subscripts, lwd = 2, ...) panel.abline(v = xp, h = yp, lty = 2, lwd = 1) lpoints(c(xp, xp), yp, cex = 1.25, col = "black", lwd = 1.5) }) ) data(BumpyGlossy, package = "MLCM") head(BumpyGlossy) library(MLCM) library(plotrix) mr <- par("mar") op <- par(mar = mr + c(0, 0, 0, 4.5), pty = "s") plot(BumpyGlossy, xlab = expression(paste("Surface ", S[ij], " Gloss Level (i) and Roughness level (j)")), ylab = expression(paste("Surface ", S[kl], " Gloss Level (k) and Roughness level (l)")) ) par(xpd = NA) gradient.rect(5.9, 1, 6.3, 5, col = grey.colors(4, 0, 0.83), gradient = "y") text(6.375, seq(1.5, 4.5, 1), formatC(round(seq(0, 1, len = 4), 2), 2, format = "f"), adj = 0) par(op) lmlcm <- function(p, d){ n <- max(d[, 2:3]) - 1 pcur <- c(0, p[1:n], 0, p[-(1:n)]) rv <- pcur[d[, 2]] - pcur[d[, 3]] + pcur[d[, 4] + 5] - pcur[d[, 5] + 5] -sum(ifelse(d[, 1] == "1", pnorm(rv, log.p = TRUE), pnorm(rv, lower.tail = FALSE, log.p = TRUE))) } p <- c(seq(0.1, 1, len = 4), seq(1, 10, len = 4)) bg.opt <- optim(p, lmlcm, d = BumpyGlossy, method = "BFGS", hessian = TRUE) bg.opt$par bg.opt$value sqrt(diag(solve(bg.opt$hessian))) opt.est <- c(0, bg.opt$par[1:4], 0, bg.opt$par[-(1:4)]) ci <- 1.96 * sqrt(diag(solve(bg.opt$hess))) ci <- c(0, ci[1:4], 0, ci[-(1:4)]) plot(opt.est[1:5], type = "l", ylim = c(0, 6), lty = 2, lwd = 2, pch = 2, xlab = "Physical Scale Values", ylab = "Perceptual Scale Values") lines(opt.est[6:10], lwd = 2, type = "l", pch = 1) segments(1:5, opt.est[1:5] + ci[1:5], 1:5, opt.est[1:5] - ci[1:5]) segments(1:5, opt.est[-(1:5)] + ci[-(1:5)], 1:5, opt.est[-(1:5)] - ci[-(1:5)]) points(opt.est[1:5], pch = 22, bg = "white") points(opt.est[6:10], pch = 21, bg = "white") make.wide <- function(d){ nr <- nrow(d) wts <- rep(c(1, -1), each = nr) ix.mat <- matrix(0, ncol = max(d), nrow = nr) ix.mat[matrix(c(rep(1:nr, 2), as.vector(unlist(d))), ncol = 2)] <- wts ix.mat <- t(apply(ix.mat, 1, function(x) if (sum(x) == 0) x else rep(0, max(d)))) ix.mat[, -1] } bg.lst <- lapply(seq(2, length(BumpyGlossy) - 1, 2), function(x, d){ make.wide(d[, x:(x+1)]) }, d = BumpyGlossy) X <- do.call(cbind, bg.lst) colnames(X) <- c(paste("G", 2:5, sep = ""), paste("B", 2:5, sep = "")) head(X) bg.df <- data.frame(resp = BumpyGlossy$Resp, X) bg.glm <- glm(resp ~ . -1, binomial(probit), bg.df) opt.est <- c(0, bg.opt$par[1:4], 0, bg.opt$par[-(1:4)]) glm.est <- c(0, bg.glm$coef[1:4], 0, bg.glm$coef[-(1:4)]) plot(opt.est[1:5], type = "l", ylim = c(0, 6), lty = 2, lwd = 2, xlab = "Physical Scale Values", ylab = "Perceptual Scale Values", cex.lab = 1.5, cex.axis = 1.3) lines(opt.est[6:10], lwd = 2) points(glm.est[1:5], pch = 22, bg = "white", cex = 1.5) points(glm.est[6:10], pch = 21, bg = "white", cex = 1.5) bg.Ind <- update(bg.glm, . ~ . - G2 - G3 - G4 - G5) anova(bg.Ind, bg.glm, test = "Chisq") make.wide.full <- function(d){ cn <- function(y, mx) (y[, 2] - 1) * mxd[2] + y[, 1] nr <- nrow(d) mxd <- c(max(d[, 1:2]), max(d[, 3:4])) nc <- prod(mxd) nms <- sapply(seq(1, ncol(d), 2), function(x) substring(names(d)[x], 1, nchar((names(d)[x])) - 1)) fnm <- mapply(paste, nms, list(seq_len(mxd[1]), seq_len(mxd[2])), sep = "", SIMPLIFY = FALSE) nms.f <- interaction(do.call(expand.grid, fnm), sep = ":") ix.mat <- matrix(0, ncol = nc, nrow = nr) ix.mat[cbind(seq_len(nr), cn(d[, c(1, 3)], mxd))] <- 1 ix.mat[cbind(seq_len(nr), cn(d[, c(2, 4)], mxd))] <- -1 ix.mat <- t(apply(ix.mat, 1, function(x) if (sum(x) == 0) x else rep(0, nc))) colnames(ix.mat) <- levels(nms.f) ix.mat[, -1] } Xf <- make.wide.full(BumpyGlossy[, -1]) bg.dff <- data.frame(resp = BumpyGlossy[, 1], Xf) bg.dff[1, ] BumpyGlossy[1, ] bg.saturated <- update(bg.glm, data = bg.dff) anova(bg.glm, bg.saturated, test = "Chisq") rm(make.wide, make.wide.full) library(MLCM) bg.add <- mlcm(BumpyGlossy) methods(class = "mlcm") bg.ind <- mlcm(BumpyGlossy, model = "ind", whichdim = 2) bg.saturated <- mlcm(BumpyGlossy, model = "full") bg.add$pscale opar <- par(mfrow = c(1,2), cex.lab = 1.5, cex.axis = 1.3) plot(bg.saturated, type = "b", lty = 1, lwd = 2, col = c("black", paste("grey", 10 + 15 * (1:4))), xlab = "Glossiness Level", ylab = "Roughness Estimates") mtext("a", 3, adj = 0, cex = 2, line = 1) plot(bg.saturated, transpose = TRUE, type = "b", lty = 1, lwd = 2, col = c("black", paste("grey", 10 + 15 * (1:4))), xlab = "Roughness Level", ylab = "Glossiness Estimates") mtext("b", 3, adj = 0, cex = 2, line = 1) par(opar) mr <- par("mar") opar <- par(mfrow = c(1, 2), mar = mr + c(0, 0, 0, 3)) bg.add.pred <- with(bg.add, outer(pscale[, 1], pscale[, 2], "+")) plot(bg.saturated, standard.scale = TRUE, type = "b", lty = 1, lwd = 2, col = c("black", paste("grey", 10 + 15 * (1:4))), ylim = c(-0.2, 1.2), xlab = "Gloss Level", ylab = "Roughness model Estimates") cf <- coef(lm(as.vector(bg.saturated$pscale/bg.saturated$pscale[5, 5]) ~ as.vector(bg.add.pred) + 0)) matplot(cf * bg.add.pred, type = "l", lty = 2, lwd = 2, col = c("black", paste("grey", 10 + 15 * (1:4))), add = TRUE) bg.saturated.sc <- bg.saturated$pscale/bg.saturated$pscale[5, 5] bg.add.adj <- cf * bg.add.pred bg.res <- (bg.add.adj - bg.saturated.sc) + 0.5 mtext("a", 3, adj = 0, cex = 2, line = 1) par(xpd = NA) gcl <- grey.colors(100, min(bg.res), max(bg.res)) image(1:5, 1:5, bg.res, col = gcl, xlab = "Gloss Level", ylab = "Roughness Level" ) dgcl <- grey.colors(100, 0, 1) gradient.rect(5.8, 1, 6.2, 5, col = dgcl, gradient = "y") ylab <- -1:1 ypos <- seq(1, 5, len = 3) text(6.7, ypos, formatC(ylab, 1, format = "f"), adj = 1) mtext("b", 3, adj = 0, cex = 2, line = 1) par(opar) bg.frm <- mlcm(~ p[1] * (x - 1)^p[2] + p[3] * (y - 1)^p[4], p = c(0.1, 1, 1.5, 0.8), data = BumpyGlossy) bg.frm$par xx <- seq(1, 5, len = 100) plot(bg.add, xlab = "Physical Scale Values", ylab = "Perceptual Scale Values") lines(xx, predict(bg.frm, newdata = xx)[seq_along(xx)]) lines(xx, predict(bg.frm, newdata = xx)[-seq_along(xx)]) anova(bg.add, bg.frm) dd <- structure(list(N = c(30, 150, 300, 63, 315, 630, 201.6, 1008, 2016, 495, 2475, 4950), SD = c(0.198804903944735, 0.0494169735922849, 0.0483475961477474, 0.11144484767624, 0.057941390390986, 0.0498386086620115, 0.0687411704173731, 0.0489132254288009, 0.035810703580535, 0.0710439540913592, 0.0282549870235406, 0.0152091769143304), ScaleLevels = c(5, 5, 5, 6, 6, 6, 8, 8, 8, 10, 10, 10), PerTrial = c(10, 50, 100, 10, 50, 100, 10, 50, 100, 10, 50, 100)), .Names = c("N", "SD", "ScaleLevels", "PerTrial"), row.names = c(NA, -12L), class = "data.frame") dd.lm <- lm(log10(SD) ~ offset(-0.5 * log10(N)), dd) plot(SD ~ N, dd, xlim = c(10, 5000), ylim = c(0.005, 0.3), log = "xy", pch = 20 + unclass(factor(dd$ScaleLevels)), cex = 1.3, bg = c("white", "grey", "black")[unclass(factor(dd$PerTrial))]) x <- 10^seq(1, 3.7, len = 100) lines(x, 10^coef(dd.lm) / sqrt(x), lwd = 2) points(SD ~ N, dd, pch = 20 + unclass(factor(dd$ScaleLevels)), cex = 1.3, bg = c("white", "grey", "black")[unclass(factor(dd$PerTrial))]) legend(10, 0.021, unique(dd$ScaleLevels^2), pch = 21:25, bty = "n", title = "Number of Stimuli" ) legend(100, 0.021, unique(dd$PerTrial), pch = 21, bty = "n", title = "%subsampling", pt.bg = c("white", "grey", "black") )
validate_get_twcv <- function( color_matrix, dbscan_eps = 20, dbscan_min_pts = 4, max_var_tight_cluster = 150, max_prop_single_tight_cluster = 0.6, safe_num_clusters = 3, safe_twcv = 250 ) { if (nrow(color_matrix) < dbscan_min_pts) { return(list( valid = FALSE, reason_invalid = "too_few_color_responses", twcv = NA, num_clusters = NA )) } dbscan_res <- dbscan::dbscan( color_matrix, eps = dbscan_eps, minPts = dbscan_min_pts ) cluster_numbers <- unique(dbscan_res$cluster) twcv <- total_within_cluster_variance(color_matrix, dbscan_res$cluster) num_noise_pts <- sum(dbscan_res$cluster == 0) noise_c_few_pts <- (num_noise_pts > 0) && (num_noise_pts < dbscan_min_pts) num_clusters <- length(cluster_numbers) - as.numeric(noise_c_few_pts) for (clu_n in cluster_numbers) { cluster_mask <- dbscan_res$cluster == clu_n num_in_cluster <- length(dbscan_res$cluster[cluster_mask]) prop_in_cluster <- num_in_cluster / length(dbscan_res$cluster) if (prop_in_cluster > max_prop_single_tight_cluster) { cluster_var <- point_3d_variance(color_matrix[cluster_mask, ]) if (cluster_var <= max_var_tight_cluster) { return(list( valid = FALSE, reason_invalid = "hi_prop_tight_cluster", twcv = twcv, num_clusters = num_clusters )) } } } twcv_score <- total_within_cluster_variance( color_matrix, dbscan_res$cluster ) few_clusters <- num_clusters < safe_num_clusters low_twcv <- twcv_score < safe_twcv if (few_clusters && low_twcv) { return(list( valid = FALSE, reason_invalid = "few_clusters_low_twcv", twcv = twcv, num_clusters = num_clusters )) } return(list( valid = TRUE, reason_invalid = "", twcv = twcv, num_clusters = num_clusters )) }
df_groceries <- read.csv("./data/groceries.csv") str(df_groceries) head(df_groceries) dim(df_groceries) df_sorted <- df_groceries[order(df_groceries$Member_number),] df_sorted df_sorted$Member_number <- as.numeric(df_sorted$Member_number) str(df_sorted) head(df_sorted) df_sorted$itemDescription <- as.factor(df_sorted$itemDescription) str(df_sorted) library(dplyr) library(plyr) ?ddply df_itemList <- ddply(df_groceries, c("Member_number","Date"), function(df1)paste(df1$itemDescription,collapse = ",")) df_itemList$Member_number <- NULL df_itemList$Date <- NULL str(df_itemList) colnames(df_itemList) <- c("itemList") str(df_itemList) head(df_itemList,n=20) df_itemList write.csv(df_itemList,"./data/ItemList.csv", row.names = TRUE) library(arules) txn = read.transactions(file="./data/ItemList.csv", rm.duplicates= TRUE, format="basket",sep=",",cols=1); txn = read.transactions(file.choose(), rm.duplicates= TRUE, format="basket",sep=",",cols=1); txn inspect(txn) txn@itemInfo$labels <- gsub("\"","",txn@itemInfo$labels) basket_rules <- apriori(txn,parameter = list(minlen=2,sup = 0.01, conf = 0.7, target="rules")) inspect(basket_rules) if(sessionInfo()['basePkgs']=="tm" | sessionInfo()['otherPkgs']=="tm"){ detach(package:sentiment, unload=TRUE) detach(package:tm, unload=TRUE) } inspect(basket_rules) df_basket <- as(basket_rules,"data.frame") df_basket$confidence <- df_basket$confidence * 100 df_basket$support <- df_basket$support * nrow(df) write.csv(df_basket,"Rules_20.csv",row.names = FALSE) library(arulesViz) plot(basket_rules) set.seed(8000) plot(basket_rules, method = "grouped", control = list(k = 5)) plot(basket_rules[1:10,], method="graph", control=list(type="items")) plot(basket_rules[1:10,], method="paracoord", control=list(alpha=.5, reorder=TRUE)) itemFrequencyPlot(txn, topN = 5) plot(basket_rules[1:10,],measure=c("support","lift"),shading="confidence",interactive=T)
fgsub <- function(x, pattern, fun, ...){ hit_id <- pattern_id <- pat <- NULL locs <- stringi::stri_detect_regex(x, pattern) locs[is.na(locs)] <- FALSE txt <- x[locs] hits <- stringi::stri_extract_all_regex(txt, pattern) h <- lengths(hits) y <- sum(h) if (y == 0) return(x) counter <- ceiling(y/26) pats <- unique(unlist(hits)) reps <- paste0("textcleanholder", seq_along(pats), "textcleanholder") freps <- unlist(lapply(pats, fun)) pat_key <- data.table::data.table(pat = reps, replacement = freps) hit_key <- data.table::data.table( hit_id = rep(seq_len(length(h)), h), pat = reps, pattern_id = unlist(lapply(h, seq_len)) ) data.table::setkey(pat_key, pat) data.table::setkey(hit_key, pat) hit_key <- hit_key[pat_key][, hit_id := as.integer(hit_id)][, pattern_id := as.integer(pattern_id)] data.table::setorderv(hit_key, cols = c('hit_id', 'pattern_id')) for (i in seq_len(y)) { hkr <- hit_key[i,] txt[hkr[, 'hit_id'][[1]]] <- sub( pattern, hkr[, 'pat'][[1]], txt[hkr[, 'hit_id'][[1]]], perl = TRUE ) } txt <- mgsub(txt, hit_key[['pat']], hit_key[['replacement']], fixed = TRUE, ...) x[locs] <- txt x }
context("Set global (uuid) identifiers") test_that("We can generate valid EML with uuid ids on all elements", { skip_if_not_installed("geiger") if(require("uuid")){ options(uuid = TRUE) data(geospiza) add_trees(geospiza$phy) nexml <- add_characters(geospiza$dat) write.nexml(nexml, file = "geospiza.xml") expect_true_or_null(nexml_validate("geospiza.xml")) unlink("geospiza.xml") } })
context("METAR time zone") x1 <- "EPWA 281830Z 18009KT 140V200 9999 SCT037 03/M01 Q1008 NOSIG" x2 <- "CYUL 281800Z 13008KT 30SM BKN240 01/M06 A3005 RMK CI5 SLP180" x3 <- "201711271930 METAR LEMD 271930Z 02002KT CAVOK 04/M03 Q1025 NOSIG= NOSIG=" x4 <- "201905121244 METAR KDCA 121244Z 05010KT 1 3/4SM R01/6000VP6000FT -RA BR OVC007 14/12 A2978 RMK AO2 P0002 T01390122" x5 <- "201905121244 SPECI KDCA 121244Z 05010KT 2 1/4SM R01/6000VP6000FT -RA BR OVC007 14/12 A2978 RMK AO2 P0002 T01390122" x6 <- "CYWG 172000Z 30015G25KT 3/4SM R36/4000FT/D -SN BLSN BKN008 OVC040 M05/M08 A2992 REFZRA WS RWY36 RMK SF5NS3 SLP134" x7 <- "METAR KJFK 282355Z AUTO 13009KT 10SM -RA SCT028 SCT035 BKN079 23/20 A2972 RMK T02300200 LTG DSNT SE-SW! MADISHF" x <- c(x1, x2, x3, x4, x5, x6, x7) dx <- data.frame(metar = x) test_that("Check time zones", { expect_equal(metar_time_zone(x1), "Z") expect_equal(metar_time_zone(x2), "Z") expect_equal(metar_time_zone(x3), "Z") expect_equal(metar_time_zone(x4), "Z") expect_equal(metar_time_zone(x5), "Z") expect_equal(metar_time_zone(x6), "Z") expect_equal(metar_time_zone(x7), "Z") expect_equal(metar_time_zone(x), c("Z", "Z", "Z", "Z", "Z", "Z", "Z")) expect_equal(metar_time_zone(dx$metar), c("Z", "Z", "Z", "Z", "Z", "Z", "Z")) }) x8 <- "EPWA 0281830Z 18009KT 140V200 9999 SCT037 03/M01 Q1008 NOSIG" x9 <- "CYU 281800Z 13008KT 30SM BKN240 01/M06 A3005 RMK CI5 SLP180" x10 <- "201711271930 METAR LEMD 271930 02002KT CAVOK 04/M03 Q1025 NOSIG= NOSIG=" test_that("Incorrect METAR reports", { expect_equal(is.na(metar_time_zone(x8)), TRUE) expect_equal(is.na(metar_time_zone(x9)), TRUE) expect_equal(is.na(metar_time_zone(x10)), TRUE) }) dx <- data.frame(metar = c(x1, x2, x3, x4, x5, x6, x7, x8, x9, x10)) test_that("Correct and incorrect METAR reports", { expect_equal(metar_time_zone(dx$metar), c("Z", "Z", "Z", "Z", "Z", "Z", "Z", NA, NA, NA)) }) dxt <- tibble::as_tibble(dx) test_that("Check invalid input format", { expect_error(metar_pressure(dx)) expect_error(metar_pressure(dxt)) })
s3saveRDS <- function(x, object = paste0(as.character(substitute(x)), ".rds"), bucket, compress = TRUE, ...) { if (missing(bucket)) { bucket <- get_bucketname(object) } object <- get_objectkey(object) tmp <- tempfile(fileext = ".rds") on.exit(unlink(tmp)) saveRDS(x, file = tmp, compress = compress) r <- put_object(file = tmp, bucket = bucket, object = object, ...) return(invisible(r)) } s3readRDS <- function(object, bucket, ...) { if (missing(bucket)) { bucket <- get_bucketname(object) } object <- get_objectkey(object) tmp <- tempfile(fileext = ".rds") on.exit(unlink(tmp)) r <- save_object(bucket = bucket, object = object, file = tmp, ...) tryCatch(readRDS(tmp), error = function(e) { if (grepl("unknown input format", as.character(e), fixed = TRUE)) { r <- readBin(tmp, "raw", n = 1e9, endian = "big") unserialize(memDecompress(from = r, "gzip")) } else { stop(e) } } ) }
getAverageSpreadOf2SubpopClades<-function(tsneResults, pacman_results){ ClusterID<-NULL l<-cbind(as.data.frame(tsneResults), pacman_results[,c(2,3)]) recurrentClades<-names(which(table(l[,3]) == 2)) l2<-l[(l[,3] %in% recurrentClades),] clade_dist_record<-vector() for(i in 1:length(recurrentClades)){ clade_subset<-subset(l2, ClusterID == recurrentClades[i]) clade_subset_info<-clade_subset[,c(3,4)] clade_subset<-clade_subset[,c(1,2)] clade_dist<-sqrt(sum(clade_subset[1,]-clade_subset[2,])^2) clade_dist_record[i]<-clade_dist } avgDist<-mean(clade_dist_record) return(avgDist) }
setMethod("cor.test", signature(x = "Nri"), function(x, y, ...) { cor_apply_lh <- function(response, ...) { predictor <- get("predictor", envir= environment_apply) t_res <- cor.test(x = predictor, y = response, ...) return(c(t_res$p.value, t_res$estimate)) } cor_apply_rh <- function(predictor, ...) { response <- get("response", envir= environment_apply) t_res <- cor.test(x = predictor, y = response, ...) return(c(t_res$p.value, t_res$estimate)) } cor_apply_both <- function(xy, ...) { t_res <- cor.test(x = xy[1:(length(xy)/2)], y = xy[(length(xy)/2+1):length(xy)], ...) return(c(t_res$p.value, t_res$estimate)) } if (class(x)[1] == "Nri") { if (class(y)[1] == "Nri") { nri_response <- NA for (i in 1:length(dim(x$nri))) if (dim(x$nri)[i]!=dim(y$nri)[i]) stop("Dimensions of nri values in x and y differ") } else { nri_response <- FALSE } nri_data <- x } else { if (class(y)[1] == "Nri") { nri_response <- TRUE nri_data <- y } else { stop("Could not determine which variable contains nri-values") } } if (is.na(nri_response)) { xy <- new("DistMat3D", values = c(x$nri, y$nri), nlyr = dim(x$nri)[3] + dim(y$nri)[3], ncol = dim(x$nri)[1]) res <- new("Nri", nri = xy, fwhm = x@fwhm, wavelength = x@wavelength, dimnames = list(Band_1 = x@dimnames[[1]], Band_2 = x@dimnames[[1]], Sample = c(x@dimnames[[1]], y@dimnames[[1]]))) cor_data <- apply(xy, MARGIN = c(1, 2), FUN = cor_apply_both, ...) } else { if (nri_response) { res <- y response <- y$nri environment_apply <- new.env(parent = .GlobalEnv) assign("predictor", x, environment_apply) cor_data <- apply(response, MARGIN = c(1, 2), FUN = cor_apply_lh, ...) } else { res <- x predictor <- x$nri environment_apply <- new.env(parent = .GlobalEnv) assign("response", y, environment_apply) cor_data <- apply(predictor, MARGIN = c(1, 2), FUN = cor_apply_rh, ...) } } final <- list(p.value = new("DistMat3D", values = cor_data[1,], ncol = dim(x$nri)[1], nlyr = 1), estimate = new("DistMat3D", values = cor_data[2,], ncol = dim(x$nri)[1], nlyr = 1) ) attr(final,"is.predictor.nri") <- nri_response attr(final,"function") <- "cor.test" res@multivariate <- final return(res) } )
.profitFerrerScale=function(mag=15, rout=3, a=1, b=1, axrat=1, box=0){ if(box!=0){Rbox=pi*(box+2)/(4*beta(1/(box+2),1+1/(box+2)))}else{Rbox=1} lumtot = (a*beta(a,1+2/(2-b)))*rout^2 * pi *axrat/Rbox; magtot = -2.5 * log10(lumtot) return(1/(10^(0.4 * (mag - magtot)))) } .profitFerrer=function(r=1, rout=3, a=1, b=1){ inten = (1-(r/rout)^(2-b))^a inten[r>rout]=0 return(inten) } .profitFerrerXY=function(args=c(0,0), xcen=0, ycen=0, rout=3, a=1, b=1, ang=0, axrat=1, box=0){ rad=sqrt((args[1]-xcen)^2+(args[2]-ycen)^2); angrad=-ang*pi/180 angmod=atan2((args[1]-xcen),(args[2]-ycen))-angrad; xmod=rad*sin(angmod); ymod=rad*cos(angmod); xmod=xmod/axrat; radmod=(abs(xmod)^(2+box)+abs(ymod)^(2+box))^(1/(2+box)) output=.profitFerrer(radmod, rout=rout, a=a, b=b) return(output) } .profitFerrerExactSumPix=function(xpix=c(0,1), ypix=c(0,1), xcen=0, ycen=0, rout=3, a=1, b=1, ang=0, axrat=1, box=0, rel.tol=1e-3, abs.tol= 1e-10){ return(hcubature(.profitFerrerXY, lowerLimit=c(xpix[1],ypix[1]), upperLimit=c(xpix[2],ypix[2]), xcen=xcen, ycen=ycen, rout=rout, a=a, b=b, ang=ang, axrat=axrat, box=box, tol=rel.tol, absError=abs.tol)$integral) } profitRadialFerrer=function(r=1, mag=15, rout=3, a=1, b=1, ang=0, axrat=1, box=0){ return= .profitFerrer(r, rout=rout, a=a, b=b)* .profitFerrerScale(mag=mag, rout=rout, a=a, b=b, axrat=axrat, box=box) } profitCubaFerrer=function(xcen=dim[1]/2, ycen=dim[2]/2, mag=15, rout=3, a=1, b=1, ang=0, axrat=1, box=0, dim=c(25,25), rel.tol=1e-3, abs.tol= 1e-10, plot=FALSE, ...){ if(length(dim)==1){dim=rep(dim,2)} xpix=0:(dim[1]-1) ypix=0:(dim[2]-1) pixgrid=expand.grid(xpix,ypix) pixval={} for(i in 1:length(pixgrid[,1])){ pixval=c(pixval, .profitFerrerExactSumPix(c(pixgrid[i,1],pixgrid[i,1]+1), c(pixgrid[i,2],pixgrid[i,2]+1), xcen=xcen, ycen=ycen, rout=rout, a=a, b=b, ang=ang, axrat=axrat, box=box, rel.tol= rel.tol, abs.tol= abs.tol)) } output=matrix(pixval*.profitFerrerScale(mag=mag, rout=rout, a=a, b=b, axrat=axrat, box=box),dim[1],dim[2]) if(plot){ magimage(output, ...) } return=output }
setClass(Class="Target", representation=representation(name="character")) setMethod( f="show", signature="Target", definition=function(object) cat(sprintf("<object of class %s>\n", class(object))) )
locofmax<-function(pcf) { d<-length(pcf$N) step<-matrix(0,d,1) for (i in 1:d){ step[i]<-(pcf$support[2*i]-pcf$support[2*i-1])/pcf$N[i] } nod<-which.max(pcf$value) lowi<-matrix(0,d,1) uppi<-matrix(0,d,1) for (jj in 1:d){ lowi[jj]<-pcf$support[2*jj-1]+step[jj]*(pcf$down[nod,jj]) uppi[jj]<-pcf$support[2*jj-1]+step[jj]*pcf$high[nod,jj] } baryc<-lowi+(uppi-lowi)/2 return(baryc) }
require(OpenMx) model <- mxModel('model') obsData <- matrix(c(1:10), 10, 1) data <- mxData(obsData, "raw") chol <- mxMatrix("Full", 2, 2, c(T,T,F,T), c(1,.2,0,1), name="Chol") expCov <- mxAlgebra(Chol %*% t(Chol), name="expCov") expMean <- mxMatrix("Full", 1, 2, T, c(0,0), "expMean") objective <- mxExpectationNormal("expCov", "expMean") foo <- mxMatrix('Full', 1, 1, name = 'foo') bar <- mxMatrix('Full', 10, 1, name = 'bar') model <- mxModel(model, data, chol, expCov, expMean, objective, foo, bar, mxFitFunctionML()) omxCheckIdentical(mxEval(objective + foo, model, TRUE), matrix(as.numeric(NA), 1, 1)) objective <- mxExpectationNormal("expCov", "expMean") model <- mxModel(model, objective, mxFitFunctionML(vector = TRUE)) omxCheckIdentical(mxEval(objective + bar, model, TRUE), matrix(as.numeric(NA), 10, 1))
library(hamcrest) Sys.setlocale('LC_COLLATE', 'C') as.vector.foo <- function(...) 41L as.vector.foo <- function(...) 99 Math.bar <- function(...) 44 Summary.bar <- function(...) 45 Ops.bar <- function(...) 46 test.as.vector.1 <- function() assertThat(as.vector(NULL), identicalTo(NULL)) test.as.vector.2 <- function() assertThat(as.vector(logical(0)), identicalTo(logical(0))) test.as.vector.3 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE)), identicalTo(c(TRUE, TRUE, FALSE, FALSE, TRUE))) test.as.vector.4 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", ""))), identicalTo(c(TRUE, FALSE))) test.as.vector.5 <- function() assertThat(as.vector(c(TRUE, FALSE, NA)), identicalTo(c(TRUE, FALSE, NA))) test.as.vector.6 <- function() assertThat(as.vector(integer(0)), identicalTo(integer(0))) test.as.vector.7 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0))), identicalTo(integer(0))) test.as.vector.8 <- function() assertThat(as.vector(1:3), identicalTo(1:3)) test.as.vector.9 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L)), identicalTo(c(1L, NA, 4L, NA, 999L))) test.as.vector.10 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L)), identicalTo(c(1L, 2L, 1073741824L, 1073741824L))) test.as.vector.11 <- function() assertThat(as.vector(numeric(0)), identicalTo(numeric(0))) test.as.vector.12 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708)), identicalTo(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), tol = 0.000100)) test.as.vector.13 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708)), identicalTo(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), tol = 0.000100)) test.as.vector.14 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b"))), identicalTo(1:2)) test.as.vector.15 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b"))), identicalTo(c(1.5, 2.5), tol = 0.000100)) test.as.vector.16 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30)), identicalTo(c(1.5, 1.51, 0, 1.49, -30), tol = 0.000100)) test.as.vector.17 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA)), identicalTo(c(1.5, 1.51, 0, 1.49, -30, NA), tol = 0.000100)) test.as.vector.18 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN)), identicalTo(c(1.5, 1.51, 0, 1.49, -30, NaN), tol = 0.000100)) test.as.vector.19 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf)), identicalTo(c(1.5, 1.51, 0, 1.49, -30, Inf), tol = 0.000100)) test.as.vector.20 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf)), identicalTo(c(1.5, 1.51, 0, 1.49, -30, -Inf), tol = 0.000100)) test.as.vector.21 <- function() assertThat(as.vector(character(0)), identicalTo(character(0))) test.as.vector.22 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA)), identicalTo(c("4.1", "blahh", "99.9", "-413", NA))) test.as.vector.23 <- function() assertThat(as.vector(complex(0)), identicalTo(complex(0))) test.as.vector.24 <- function() assertThat(as.vector(list(1, 2, 3)), identicalTo(list(1, 2, 3))) test.as.vector.25 <- function() assertThat(as.vector(list(1, 2, NULL)), identicalTo(list(1, 2, NULL))) test.as.vector.26 <- function() assertThat(as.vector(list(1L, 2L, 3L)), identicalTo(list(1L, 2L, 3L))) test.as.vector.27 <- function() assertThat(as.vector(list(1L, 2L, NULL)), identicalTo(list(1L, 2L, NULL))) test.as.vector.28 <- function() assertThat(as.vector(list(1, 2, list(3, 4))), identicalTo(list(1, 2, list(3, 4)))) test.as.vector.29 <- function() assertThat(as.vector(list(1, 2, numeric(0))), identicalTo(list(1, 2, numeric(0)))) test.as.vector.30 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z")))), identicalTo(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))))) test.as.vector.31 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b"))), identicalTo(structure(list("NA" = 1, 2, b = 3), .Names = c(NA, "", "b")))) test.as.vector.32 <- function() assertThat(as.vector(pairlist(41, "a", 21L)), identicalTo(pairlist(41, "a", 21L))) test.as.vector.33 <- function() assertThat(as.vector(pairlist(a = 41, 42)), identicalTo(pairlist(a = 41, 42))) test.as.vector.34 <- function() assertThat(as.vector(pairlist(a = 41, NULL)), identicalTo(pairlist(a = 41, NULL))) test.as.vector.35 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4)), identicalTo(1:12)) test.as.vector.36 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y")))), identicalTo(1:12)) test.as.vector.37 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L)), identicalTo(1:3)) test.as.vector.38 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c")))), identicalTo(1:3)) test.as.vector.39 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z"))), identicalTo(1:3)) test.as.vector.40 <- function() assertThat(as.vector(structure(list("foo"), class = "foo")), identicalTo(99)) test.as.vector.41 <- function() assertThat(as.vector(structure(list("bar"), class = "foo")), identicalTo(99)) test.as.vector.42 <- function() assertThat(as.vector(quote(xyz)), throwsError()) test.as.vector.43 <- function() assertThat(as.vector(quote(sin(3.14))), deparsesTo("sin(3.14)")) test.as.vector.44 <- function() assertThat(as.vector("NaN"), identicalTo("NaN")) test.as.vector.45 <- function() assertThat(as.vector("NABOOM!"), identicalTo("NABOOM!")) test.as.vector.46 <- function() assertThat(as.vector("NaNaNabooboo"), identicalTo("NaNaNabooboo")) test.as.vector.47 <- function() assertThat(as.vector("-Inf"), identicalTo("-Inf")) test.as.vector.48 <- function() assertThat(as.vector("+Infinity"), identicalTo("+Infinity")) test.as.vector.49 <- function() assertThat(as.vector("Infinity and beyond!"), identicalTo("Infinity and beyond!")) test.as.vector.50 <- function() assertThat(as.vector("Infi"), identicalTo("Infi")) test.as.vector.51 <- function() assertThat(as.vector("0.03f"), identicalTo("0.03f")) test.as.vector.52 <- function() assertThat(as.vector(" 0.0330 "), identicalTo(" 0.0330 ")) test.as.vector.53 <- function() assertThat(as.vector(structure("foo", class = "foo")), identicalTo(99)) test.as.vector.54 <- function() assertThat(as.vector(structure(list(1L, "bar"), class = "bar")), identicalTo(structure(list(1L, "bar"), class = "bar"))) test.as.vector.55 <- function() assertThat(as.vector(NULL, mode = "any"), identicalTo(NULL)) test.as.vector.56 <- function() assertThat(as.vector(NULL, mode = "logical"), identicalTo(logical(0))) test.as.vector.57 <- function() assertThat(as.vector(NULL, mode = "integer"), identicalTo(integer(0))) test.as.vector.58 <- function() assertThat(as.vector(NULL, mode = "numeric"), identicalTo(numeric(0))) test.as.vector.59 <- function() assertThat(as.vector(NULL, mode = "double"), identicalTo(numeric(0))) test.as.vector.60 <- function() assertThat(as.vector(NULL, mode = "complex"), identicalTo(complex(0))) test.as.vector.61 <- function() assertThat(as.vector(NULL, mode = "raw"), identicalTo(raw(0))) test.as.vector.62 <- function() assertThat(as.vector(NULL, mode = "character"), identicalTo(character(0))) test.as.vector.63 <- function() assertThat(as.vector(NULL, mode = "list"), identicalTo(list())) test.as.vector.64 <- function() assertThat(as.vector(NULL, mode = "expression"), deparsesTo("expression(NULL)")) test.as.vector.65 <- function() assertThat(as.vector(NULL, mode = "rubish"), throwsError()) test.as.vector.66 <- function() assertThat(as.vector(NULL, mode = NA_character_), throwsError()) test.as.vector.67 <- function() assertThat(as.vector(logical(0), mode = "any"), identicalTo(logical(0))) test.as.vector.68 <- function() assertThat(as.vector(logical(0), mode = "logical"), identicalTo(logical(0))) test.as.vector.69 <- function() assertThat(as.vector(logical(0), mode = "integer"), identicalTo(integer(0))) test.as.vector.70 <- function() assertThat(as.vector(logical(0), mode = "numeric"), identicalTo(numeric(0))) test.as.vector.71 <- function() assertThat(as.vector(logical(0), mode = "double"), identicalTo(numeric(0))) test.as.vector.72 <- function() assertThat(as.vector(logical(0), mode = "complex"), identicalTo(complex(0))) test.as.vector.73 <- function() assertThat(as.vector(logical(0), mode = "raw"), identicalTo(raw(0))) test.as.vector.74 <- function() assertThat(as.vector(logical(0), mode = "character"), identicalTo(character(0))) test.as.vector.75 <- function() assertThat(as.vector(logical(0), mode = "list"), identicalTo(list())) test.as.vector.76 <- function() assertThat(as.vector(logical(0), mode = "expression"), deparsesTo("expression()")) test.as.vector.77 <- function() assertThat(as.vector(logical(0), mode = "rubish"), throwsError()) test.as.vector.78 <- function() assertThat(as.vector(logical(0), mode = NA_character_), throwsError()) test.as.vector.79 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "any"), identicalTo(c(TRUE, TRUE, FALSE, FALSE, TRUE))) test.as.vector.80 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "logical"), identicalTo(c(TRUE, TRUE, FALSE, FALSE, TRUE))) test.as.vector.81 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "integer"), identicalTo(c(1L, 1L, 0L, 0L, 1L))) test.as.vector.82 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "numeric"), identicalTo(c(1, 1, 0, 0, 1))) test.as.vector.83 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "double"), identicalTo(c(1, 1, 0, 0, 1))) test.as.vector.84 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "complex"), identicalTo(c(1+0i, 1+0i, 0+0i, 0+0i, 1+0i))) test.as.vector.85 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "raw"), identicalTo(as.raw(c(0x01, 0x01, 0x00, 0x00, 0x01)))) test.as.vector.86 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "character"), identicalTo(c("TRUE", "TRUE", "FALSE", "FALSE", "TRUE"))) test.as.vector.87 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "list"), identicalTo(list(TRUE, TRUE, FALSE, FALSE, TRUE))) test.as.vector.88 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "expression"), deparsesTo("expression(TRUE, TRUE, FALSE, FALSE, TRUE)")) test.as.vector.89 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = "rubish"), throwsError()) test.as.vector.90 <- function() assertThat(as.vector(c(TRUE, TRUE, FALSE, FALSE, TRUE), mode = NA_character_), throwsError()) test.as.vector.91 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "any"), identicalTo(c(TRUE, FALSE))) test.as.vector.92 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "logical"), identicalTo(c(TRUE, FALSE))) test.as.vector.93 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "integer"), identicalTo(c(1L, 0L))) test.as.vector.94 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "numeric"), identicalTo(c(1, 0))) test.as.vector.95 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "double"), identicalTo(c(1, 0))) test.as.vector.96 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "complex"), identicalTo(c(1+0i, 0+0i))) test.as.vector.97 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "raw"), identicalTo(as.raw(c(0x01, 0x00)))) test.as.vector.98 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "character"), identicalTo(c("TRUE", "FALSE"))) test.as.vector.99 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "list"), identicalTo(structure(list(a = TRUE, FALSE), .Names = c("a", "")))) test.as.vector.100 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "expression"), deparsesTo("expression(TRUE, FALSE)")) test.as.vector.101 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = "rubish"), throwsError()) test.as.vector.102 <- function() assertThat(as.vector(structure(c(TRUE, FALSE), .Names = c("a", "")), mode = NA_character_), throwsError()) test.as.vector.103 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "any"), identicalTo(c(TRUE, FALSE, NA))) test.as.vector.104 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "logical"), identicalTo(c(TRUE, FALSE, NA))) test.as.vector.105 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "integer"), identicalTo(c(1L, 0L, NA))) test.as.vector.106 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "numeric"), identicalTo(c(1, 0, NA))) test.as.vector.107 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "double"), identicalTo(c(1, 0, NA))) test.as.vector.108 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "complex"), identicalTo(c(1+0i, 0+0i, NA))) test.as.vector.109 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "raw"), identicalTo(as.raw(c(0x01, 0x00, 0x00)))) test.as.vector.110 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "character"), identicalTo(c("TRUE", "FALSE", NA))) test.as.vector.111 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "list"), identicalTo(list(TRUE, FALSE, NA))) test.as.vector.112 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "expression"), deparsesTo("expression(TRUE, FALSE, NA)")) test.as.vector.113 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = "rubish"), throwsError()) test.as.vector.114 <- function() assertThat(as.vector(c(TRUE, FALSE, NA), mode = NA_character_), throwsError()) test.as.vector.115 <- function() assertThat(as.vector(integer(0), mode = "any"), identicalTo(integer(0))) test.as.vector.116 <- function() assertThat(as.vector(integer(0), mode = "logical"), identicalTo(logical(0))) test.as.vector.117 <- function() assertThat(as.vector(integer(0), mode = "integer"), identicalTo(integer(0))) test.as.vector.118 <- function() assertThat(as.vector(integer(0), mode = "numeric"), identicalTo(numeric(0))) test.as.vector.119 <- function() assertThat(as.vector(integer(0), mode = "double"), identicalTo(numeric(0))) test.as.vector.120 <- function() assertThat(as.vector(integer(0), mode = "complex"), identicalTo(complex(0))) test.as.vector.121 <- function() assertThat(as.vector(integer(0), mode = "raw"), identicalTo(raw(0))) test.as.vector.122 <- function() assertThat(as.vector(integer(0), mode = "character"), identicalTo(character(0))) test.as.vector.123 <- function() assertThat(as.vector(integer(0), mode = "list"), identicalTo(list())) test.as.vector.124 <- function() assertThat(as.vector(integer(0), mode = "expression"), deparsesTo("expression()")) test.as.vector.125 <- function() assertThat(as.vector(integer(0), mode = "rubish"), throwsError()) test.as.vector.126 <- function() assertThat(as.vector(integer(0), mode = NA_character_), throwsError()) test.as.vector.127 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "any"), identicalTo(integer(0))) test.as.vector.128 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "logical"), identicalTo(logical(0))) test.as.vector.129 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "integer"), identicalTo(integer(0))) test.as.vector.130 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "numeric"), identicalTo(numeric(0))) test.as.vector.131 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "double"), identicalTo(numeric(0))) test.as.vector.132 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "complex"), identicalTo(complex(0))) test.as.vector.133 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "raw"), identicalTo(raw(0))) test.as.vector.134 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "character"), identicalTo(character(0))) test.as.vector.135 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "list"), identicalTo(structure(list(), .Names = character(0)))) test.as.vector.136 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "expression"), deparsesTo("expression()")) test.as.vector.137 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = "rubish"), throwsError()) test.as.vector.138 <- function() assertThat(as.vector(structure(integer(0), .Names = character(0)), mode = NA_character_), throwsError()) test.as.vector.139 <- function() assertThat(as.vector(1:3, mode = "any"), identicalTo(1:3)) test.as.vector.140 <- function() assertThat(as.vector(1:3, mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE))) test.as.vector.141 <- function() assertThat(as.vector(1:3, mode = "integer"), identicalTo(1:3)) test.as.vector.142 <- function() assertThat(as.vector(1:3, mode = "numeric"), identicalTo(c(1, 2, 3))) test.as.vector.143 <- function() assertThat(as.vector(1:3, mode = "double"), identicalTo(c(1, 2, 3))) test.as.vector.144 <- function() assertThat(as.vector(1:3, mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i))) test.as.vector.145 <- function() assertThat(as.vector(1:3, mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03)))) test.as.vector.146 <- function() assertThat(as.vector(1:3, mode = "character"), identicalTo(c("1", "2", "3"))) test.as.vector.147 <- function() assertThat(as.vector(1:3, mode = "list"), identicalTo(list(1L, 2L, 3L))) test.as.vector.148 <- function() assertThat(as.vector(1:3, mode = "expression"), deparsesTo("expression(1L, 2L, 3L)")) test.as.vector.149 <- function() assertThat(as.vector(1:3, mode = "rubish"), throwsError()) test.as.vector.150 <- function() assertThat(as.vector(1:3, mode = NA_character_), throwsError()) test.as.vector.151 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "any"), identicalTo(c(1L, NA, 4L, NA, 999L))) test.as.vector.152 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "logical"), identicalTo(c(TRUE, NA, TRUE, NA, TRUE))) test.as.vector.153 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "integer"), identicalTo(c(1L, NA, 4L, NA, 999L))) test.as.vector.154 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "numeric"), identicalTo(c(1, NA, 4, NA, 999))) test.as.vector.155 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "double"), identicalTo(c(1, NA, 4, NA, 999))) test.as.vector.156 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "complex"), identicalTo(c(1+0i, NA, 4+0i, NA, 999+0i))) test.as.vector.157 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "raw"), identicalTo(as.raw(c(0x01, 0x00, 0x04, 0x00, 0x00)))) test.as.vector.158 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "character"), identicalTo(c("1", NA, "4", NA, "999"))) test.as.vector.159 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "list"), identicalTo(list(1L, NA_integer_, 4L, NA_integer_, 999L))) test.as.vector.160 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "expression"), deparsesTo("expression(1L, NA_integer_, 4L, NA_integer_, 999L)")) test.as.vector.161 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = "rubish"), throwsError()) test.as.vector.162 <- function() assertThat(as.vector(c(1L, NA, 4L, NA, 999L), mode = NA_character_), throwsError()) test.as.vector.163 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "any"), identicalTo(c(1L, 2L, 1073741824L, 1073741824L))) test.as.vector.164 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE, TRUE))) test.as.vector.165 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "integer"), identicalTo(c(1L, 2L, 1073741824L, 1073741824L))) test.as.vector.166 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "numeric"), identicalTo(c(1, 2, 1073741824, 1073741824), tol = 0.000100)) test.as.vector.167 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "double"), identicalTo(c(1, 2, 1073741824, 1073741824), tol = 0.000100)) test.as.vector.168 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "complex"), identicalTo(c(1+0i, 2+0i, 1073741824+0i, 1073741824+0i))) test.as.vector.169 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x00, 0x00)))) test.as.vector.170 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "character"), identicalTo(c("1", "2", "1073741824", "1073741824"))) test.as.vector.171 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "list"), identicalTo(list(1L, 2L, 1073741824L, 1073741824L))) test.as.vector.172 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "expression"), deparsesTo("expression(1L, 2L, 1073741824L, 1073741824L)")) test.as.vector.173 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = "rubish"), throwsError()) test.as.vector.174 <- function() assertThat(as.vector(c(1L, 2L, 1073741824L, 1073741824L), mode = NA_character_), throwsError()) test.as.vector.175 <- function() assertThat(as.vector(numeric(0), mode = "any"), identicalTo(numeric(0))) test.as.vector.176 <- function() assertThat(as.vector(numeric(0), mode = "logical"), identicalTo(logical(0))) test.as.vector.177 <- function() assertThat(as.vector(numeric(0), mode = "integer"), identicalTo(integer(0))) test.as.vector.178 <- function() assertThat(as.vector(numeric(0), mode = "numeric"), identicalTo(numeric(0))) test.as.vector.179 <- function() assertThat(as.vector(numeric(0), mode = "double"), identicalTo(numeric(0))) test.as.vector.180 <- function() assertThat(as.vector(numeric(0), mode = "complex"), identicalTo(complex(0))) test.as.vector.181 <- function() assertThat(as.vector(numeric(0), mode = "raw"), identicalTo(raw(0))) test.as.vector.182 <- function() assertThat(as.vector(numeric(0), mode = "character"), identicalTo(character(0))) test.as.vector.183 <- function() assertThat(as.vector(numeric(0), mode = "list"), identicalTo(list())) test.as.vector.184 <- function() assertThat(as.vector(numeric(0), mode = "expression"), deparsesTo("expression()")) test.as.vector.185 <- function() assertThat(as.vector(numeric(0), mode = "rubish"), throwsError()) test.as.vector.186 <- function() assertThat(as.vector(numeric(0), mode = NA_character_), throwsError()) test.as.vector.187 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "any"), identicalTo(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), tol = 0.000100)) test.as.vector.188 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE, TRUE, TRUE))) test.as.vector.189 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "integer"), identicalTo(c(3L, 6L, 9L, 12L, 15L))) test.as.vector.190 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "numeric"), identicalTo(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), tol = 0.000100)) test.as.vector.191 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "double"), identicalTo(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), tol = 0.000100)) test.as.vector.192 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "complex"), identicalTo(c(3.14159+0i, 6.28319+0i, 9.42478+0i, 12.5664+0i, 15.708+0i))) test.as.vector.193 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "raw"), identicalTo(as.raw(c(0x03, 0x06, 0x09, 0x0c, 0x0f)))) test.as.vector.194 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "character"), identicalTo(c("3.14159", "6.28319", "9.42478", "12.5664", "15.708"))) test.as.vector.195 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "list"), identicalTo(list(3.14159, 6.28319, 9.42478, 12.5664, 15.708))) test.as.vector.196 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "expression"), deparsesTo("expression(3.14159, 6.28319, 9.42478, 12.5664, 15.708)")) test.as.vector.197 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = "rubish"), throwsError()) test.as.vector.198 <- function() assertThat(as.vector(c(3.14159, 6.28319, 9.42478, 12.5664, 15.708), mode = NA_character_), throwsError()) test.as.vector.199 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "any"), identicalTo(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), tol = 0.000100)) test.as.vector.200 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE, TRUE, TRUE))) test.as.vector.201 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "integer"), identicalTo(c(-3L, -6L, -9L, -12L, -15L))) test.as.vector.202 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "numeric"), identicalTo(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), tol = 0.000100)) test.as.vector.203 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "double"), identicalTo(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), tol = 0.000100)) test.as.vector.204 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "complex"), identicalTo(c(-3.14159+0i, -6.28319+0i, -9.42478+0i, -12.5664+0i, -15.708+0i))) test.as.vector.205 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "raw"), identicalTo(as.raw(c(0x00, 0x00, 0x00, 0x00, 0x00)))) test.as.vector.206 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "character"), identicalTo(c("-3.14159", "-6.28319", "-9.42478", "-12.5664", "-15.708"))) test.as.vector.207 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "list"), identicalTo(list(-3.14159, -6.28319, -9.42478, -12.5664, -15.708))) test.as.vector.208 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "expression"), deparsesTo("expression(-3.14159, -6.28319, -9.42478, -12.5664, -15.708)")) test.as.vector.209 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = "rubish"), throwsError()) test.as.vector.210 <- function() assertThat(as.vector(c(-3.14159, -6.28319, -9.42478, -12.5664, -15.708), mode = NA_character_), throwsError()) test.as.vector.211 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "any"), identicalTo(1:2)) test.as.vector.212 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "logical"), identicalTo(c(TRUE, TRUE))) test.as.vector.213 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "integer"), identicalTo(1:2)) test.as.vector.214 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "numeric"), identicalTo(c(1, 2))) test.as.vector.215 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "double"), identicalTo(c(1, 2))) test.as.vector.216 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "complex"), identicalTo(c(1+0i, 2+0i))) test.as.vector.217 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02)))) test.as.vector.218 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "character"), identicalTo(c("1", "2"))) test.as.vector.219 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "list"), identicalTo(structure(list(a = 1L, b = 2L), .Names = c("a", "b")))) test.as.vector.220 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "expression"), deparsesTo("expression(1L, 2L)")) test.as.vector.221 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = "rubish"), throwsError()) test.as.vector.222 <- function() assertThat(as.vector(structure(1:2, .Names = c("a", "b")), mode = NA_character_), throwsError()) test.as.vector.223 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "any"), identicalTo(c(1.5, 2.5), tol = 0.000100)) test.as.vector.224 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "logical"), identicalTo(c(TRUE, TRUE))) test.as.vector.225 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "integer"), identicalTo(1:2)) test.as.vector.226 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "numeric"), identicalTo(c(1.5, 2.5), tol = 0.000100)) test.as.vector.227 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "double"), identicalTo(c(1.5, 2.5), tol = 0.000100)) test.as.vector.228 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "complex"), identicalTo(c(1.5+0i, 2.5+0i))) test.as.vector.229 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02)))) test.as.vector.230 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "character"), identicalTo(c("1.5", "2.5"))) test.as.vector.231 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "list"), identicalTo(structure(list(a = 1.5, b = 2.5), .Names = c("a", "b")))) test.as.vector.232 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "expression"), deparsesTo("expression(1.5, 2.5)")) test.as.vector.233 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = "rubish"), throwsError()) test.as.vector.234 <- function() assertThat(as.vector(structure(c(1.5, 2.5), .Names = c("a", "b")), mode = NA_character_), throwsError()) test.as.vector.235 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "any"), identicalTo(c(1.5, 1.51, 0, 1.49, -30), tol = 0.000100)) test.as.vector.236 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "logical"), identicalTo(c(TRUE, TRUE, FALSE, TRUE, TRUE))) test.as.vector.237 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "integer"), identicalTo(c(1L, 1L, 0L, 1L, -30L))) test.as.vector.238 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "numeric"), identicalTo(c(1.5, 1.51, 0, 1.49, -30), tol = 0.000100)) test.as.vector.239 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "double"), identicalTo(c(1.5, 1.51, 0, 1.49, -30), tol = 0.000100)) test.as.vector.240 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "complex"), identicalTo(c(1.5+0i, 1.51+0i, 0+0i, 1.49+0i, -30+0i))) test.as.vector.241 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "raw"), identicalTo(as.raw(c(0x01, 0x01, 0x00, 0x01, 0x00)))) test.as.vector.242 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "character"), identicalTo(c("1.5", "1.51", "0", "1.49", "-30"))) test.as.vector.243 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "list"), identicalTo(list(1.5, 1.51, 0, 1.49, -30))) test.as.vector.244 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "expression"), deparsesTo("expression(1.5, 1.51, 0, 1.49, -30)")) test.as.vector.245 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = "rubish"), throwsError()) test.as.vector.246 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30), mode = NA_character_), throwsError()) test.as.vector.247 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "any"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, NA), tol = 0.000100)) test.as.vector.248 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "logical"), identicalTo(c(TRUE, TRUE, FALSE, TRUE, TRUE, NA))) test.as.vector.249 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "integer"), identicalTo(c(1L, 1L, 0L, 1L, -30L, NA))) test.as.vector.250 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "numeric"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, NA), tol = 0.000100)) test.as.vector.251 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "double"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, NA), tol = 0.000100)) test.as.vector.252 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "complex"), identicalTo(c(1.5+0i, 1.51+0i, 0+0i, 1.49+0i, -30+0i, complex(real=NA, imaginary=0)))) test.as.vector.253 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "raw"), identicalTo(as.raw(c(0x01, 0x01, 0x00, 0x01, 0x00, 0x00)))) test.as.vector.254 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "character"), identicalTo(c("1.5", "1.51", "0", "1.49", "-30", NA))) test.as.vector.255 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "list"), identicalTo(list(1.5, 1.51, 0, 1.49, -30, NA_real_))) test.as.vector.256 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "expression"), deparsesTo("expression(1.5, 1.51, 0, 1.49, -30, NA_real_)")) test.as.vector.257 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = "rubish"), throwsError()) test.as.vector.258 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NA), mode = NA_character_), throwsError()) test.as.vector.259 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "any"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, NaN), tol = 0.000100)) test.as.vector.260 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "logical"), identicalTo(c(TRUE, TRUE, FALSE, TRUE, TRUE, NA))) test.as.vector.261 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "integer"), identicalTo(c(1L, 1L, 0L, 1L, -30L, NA))) test.as.vector.262 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "numeric"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, NaN), tol = 0.000100)) test.as.vector.263 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "double"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, NaN), tol = 0.000100)) test.as.vector.264 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "complex"), identicalTo(c(1.5+0i, 1.51+0i, 0+0i, 1.49+0i, -30+0i, complex(real=NaN, imaginary=0)))) test.as.vector.265 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "raw"), identicalTo(as.raw(c(0x01, 0x01, 0x00, 0x01, 0x00, 0x00)))) test.as.vector.266 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "character"), identicalTo(c("1.5", "1.51", "0", "1.49", "-30", "NaN"))) test.as.vector.267 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "list"), identicalTo(list(1.5, 1.51, 0, 1.49, -30, NaN))) test.as.vector.268 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "expression"), deparsesTo("expression(1.5, 1.51, 0, 1.49, -30, NaN)")) test.as.vector.269 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = "rubish"), throwsError()) test.as.vector.270 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, NaN), mode = NA_character_), throwsError()) test.as.vector.271 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "any"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, Inf), tol = 0.000100)) test.as.vector.272 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "logical"), identicalTo(c(TRUE, TRUE, FALSE, TRUE, TRUE, TRUE))) test.as.vector.273 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "integer"), identicalTo(c(1L, 1L, 0L, 1L, -30L, NA))) test.as.vector.274 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "numeric"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, Inf), tol = 0.000100)) test.as.vector.275 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "double"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, Inf), tol = 0.000100)) test.as.vector.276 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "complex"), identicalTo(c(1.5+0i, 1.51+0i, 0+0i, 1.49+0i, -30+0i, Inf+0i))) test.as.vector.277 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "raw"), identicalTo(as.raw(c(0x01, 0x01, 0x00, 0x01, 0x00, 0x00)))) test.as.vector.278 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "character"), identicalTo(c("1.5", "1.51", "0", "1.49", "-30", "Inf"))) test.as.vector.279 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "list"), identicalTo(list(1.5, 1.51, 0, 1.49, -30, Inf))) test.as.vector.280 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "expression"), deparsesTo("expression(1.5, 1.51, 0, 1.49, -30, Inf)")) test.as.vector.281 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = "rubish"), throwsError()) test.as.vector.282 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, Inf), mode = NA_character_), throwsError()) test.as.vector.283 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "any"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, -Inf), tol = 0.000100)) test.as.vector.284 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "logical"), identicalTo(c(TRUE, TRUE, FALSE, TRUE, TRUE, TRUE))) test.as.vector.285 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "integer"), identicalTo(c(1L, 1L, 0L, 1L, -30L, NA))) test.as.vector.286 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "numeric"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, -Inf), tol = 0.000100)) test.as.vector.287 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "double"), identicalTo(c(1.5, 1.51, 0, 1.49, -30, -Inf), tol = 0.000100)) test.as.vector.288 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "complex"), identicalTo(c(1.5+0i, 1.51+0i, 0+0i, 1.49+0i, -30+0i, -Inf+0i))) test.as.vector.289 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "raw"), identicalTo(as.raw(c(0x01, 0x01, 0x00, 0x01, 0x00, 0x00)))) test.as.vector.290 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "character"), identicalTo(c("1.5", "1.51", "0", "1.49", "-30", "-Inf"))) test.as.vector.291 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "list"), identicalTo(list(1.5, 1.51, 0, 1.49, -30, -Inf))) test.as.vector.292 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "expression"), deparsesTo("expression(1.5, 1.51, 0, 1.49, -30, -Inf)")) test.as.vector.293 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = "rubish"), throwsError()) test.as.vector.294 <- function() assertThat(as.vector(c(1.5, 1.51, 0, 1.49, -30, -Inf), mode = NA_character_), throwsError()) test.as.vector.295 <- function() assertThat(as.vector(character(0), mode = "any"), identicalTo(character(0))) test.as.vector.296 <- function() assertThat(as.vector(character(0), mode = "logical"), identicalTo(logical(0))) test.as.vector.297 <- function() assertThat(as.vector(character(0), mode = "integer"), identicalTo(integer(0))) test.as.vector.298 <- function() assertThat(as.vector(character(0), mode = "numeric"), identicalTo(numeric(0))) test.as.vector.299 <- function() assertThat(as.vector(character(0), mode = "double"), identicalTo(numeric(0))) test.as.vector.300 <- function() assertThat(as.vector(character(0), mode = "complex"), identicalTo(complex(0))) test.as.vector.301 <- function() assertThat(as.vector(character(0), mode = "raw"), identicalTo(raw(0))) test.as.vector.302 <- function() assertThat(as.vector(character(0), mode = "character"), identicalTo(character(0))) test.as.vector.303 <- function() assertThat(as.vector(character(0), mode = "list"), identicalTo(list())) test.as.vector.304 <- function() assertThat(as.vector(character(0), mode = "expression"), deparsesTo("expression()")) test.as.vector.305 <- function() assertThat(as.vector(character(0), mode = "rubish"), throwsError()) test.as.vector.306 <- function() assertThat(as.vector(character(0), mode = NA_character_), throwsError()) test.as.vector.307 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "any"), identicalTo(c("4.1", "blahh", "99.9", "-413", NA))) test.as.vector.308 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "logical"), identicalTo(c(NA, NA, NA, NA, NA))) test.as.vector.309 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "integer"), identicalTo(c(4L, NA, 99L, -413L, NA))) test.as.vector.310 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "numeric"), identicalTo(c(4.1, NA, 99.9, -413, NA), tol = 0.000100)) test.as.vector.311 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "double"), identicalTo(c(4.1, NA, 99.9, -413, NA), tol = 0.000100)) test.as.vector.312 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "complex"), identicalTo(c(4.1+0i, NA, 99.9+0i, -413+0i, NA))) test.as.vector.313 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "raw"), identicalTo(as.raw(c(0x04, 0x00, 0x63, 0x00, 0x00)))) test.as.vector.314 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "character"), identicalTo(c("4.1", "blahh", "99.9", "-413", NA))) test.as.vector.315 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "list"), identicalTo(list("4.1", "blahh", "99.9", "-413", NA_character_))) test.as.vector.316 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "expression"), deparsesTo("expression(\"4.1\", \"blahh\", \"99.9\", \"-413\", NA_character_)")) test.as.vector.317 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = "rubish"), throwsError()) test.as.vector.318 <- function() assertThat(as.vector(c("4.1", "blahh", "99.9", "-413", NA), mode = NA_character_), throwsError()) test.as.vector.319 <- function() assertThat(as.vector(complex(0), mode = "any"), identicalTo(complex(0))) test.as.vector.320 <- function() assertThat(as.vector(complex(0), mode = "logical"), identicalTo(logical(0))) test.as.vector.321 <- function() assertThat(as.vector(complex(0), mode = "integer"), identicalTo(integer(0))) test.as.vector.322 <- function() assertThat(as.vector(complex(0), mode = "numeric"), identicalTo(numeric(0))) test.as.vector.323 <- function() assertThat(as.vector(complex(0), mode = "double"), identicalTo(numeric(0))) test.as.vector.324 <- function() assertThat(as.vector(complex(0), mode = "complex"), identicalTo(complex(0))) test.as.vector.325 <- function() assertThat(as.vector(complex(0), mode = "raw"), identicalTo(raw(0))) test.as.vector.326 <- function() assertThat(as.vector(complex(0), mode = "character"), identicalTo(character(0))) test.as.vector.327 <- function() assertThat(as.vector(complex(0), mode = "list"), identicalTo(list())) test.as.vector.328 <- function() assertThat(as.vector(complex(0), mode = "expression"), deparsesTo("expression()")) test.as.vector.329 <- function() assertThat(as.vector(complex(0), mode = "rubish"), throwsError()) test.as.vector.330 <- function() assertThat(as.vector(complex(0), mode = NA_character_), throwsError()) test.as.vector.331 <- function() assertThat(as.vector(list(1, 2, 3), mode = "any"), identicalTo(list(1, 2, 3))) test.as.vector.332 <- function() assertThat(as.vector(list(1, 2, 3), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE))) test.as.vector.333 <- function() assertThat(as.vector(list(1, 2, 3), mode = "integer"), identicalTo(1:3)) test.as.vector.334 <- function() assertThat(as.vector(list(1, 2, 3), mode = "numeric"), identicalTo(c(1, 2, 3))) test.as.vector.335 <- function() assertThat(as.vector(list(1, 2, 3), mode = "double"), identicalTo(c(1, 2, 3))) test.as.vector.336 <- function() assertThat(as.vector(list(1, 2, 3), mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i))) test.as.vector.337 <- function() assertThat(as.vector(list(1, 2, 3), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03)))) test.as.vector.338 <- function() assertThat(as.vector(list(1, 2, 3), mode = "character"), identicalTo(c("1", "2", "3"))) test.as.vector.339 <- function() assertThat(as.vector(list(1, 2, 3), mode = "list"), identicalTo(list(1, 2, 3))) test.as.vector.340 <- function() assertThat(as.vector(list(1, 2, 3), mode = "expression"), deparsesTo("expression(1, 2, 3)")) test.as.vector.341 <- function() assertThat(as.vector(list(1, 2, 3), mode = "rubish"), throwsError()) test.as.vector.342 <- function() assertThat(as.vector(list(1, 2, 3), mode = NA_character_), throwsError()) test.as.vector.343 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "any"), identicalTo(list(1, 2, NULL))) test.as.vector.344 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "logical"), throwsError()) test.as.vector.345 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "integer"), throwsError()) test.as.vector.346 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "numeric"), throwsError()) test.as.vector.347 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "double"), throwsError()) test.as.vector.348 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "complex"), throwsError()) test.as.vector.349 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "raw"), throwsError()) test.as.vector.350 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "character"), identicalTo(c("1", "2", "NULL"))) test.as.vector.351 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "list"), identicalTo(list(1, 2, NULL))) test.as.vector.352 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "expression"), deparsesTo("expression(1, 2, NULL)")) test.as.vector.353 <- function() assertThat(as.vector(list(1, 2, NULL), mode = "rubish"), throwsError()) test.as.vector.354 <- function() assertThat(as.vector(list(1, 2, NULL), mode = NA_character_), throwsError()) test.as.vector.355 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "any"), identicalTo(list(1L, 2L, 3L))) test.as.vector.356 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE))) test.as.vector.357 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "integer"), identicalTo(1:3)) test.as.vector.358 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "numeric"), identicalTo(c(1, 2, 3))) test.as.vector.359 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "double"), identicalTo(c(1, 2, 3))) test.as.vector.360 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i))) test.as.vector.361 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03)))) test.as.vector.362 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "character"), identicalTo(c("1", "2", "3"))) test.as.vector.363 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "list"), identicalTo(list(1L, 2L, 3L))) test.as.vector.364 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "expression"), deparsesTo("expression(1L, 2L, 3L)")) test.as.vector.365 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = "rubish"), throwsError()) test.as.vector.366 <- function() assertThat(as.vector(list(1L, 2L, 3L), mode = NA_character_), throwsError()) test.as.vector.367 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "any"), identicalTo(list(1L, 2L, NULL))) test.as.vector.368 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "logical"), throwsError()) test.as.vector.369 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "integer"), throwsError()) test.as.vector.370 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "numeric"), throwsError()) test.as.vector.371 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "double"), throwsError()) test.as.vector.372 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "complex"), throwsError()) test.as.vector.373 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "raw"), throwsError()) test.as.vector.374 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "character"), identicalTo(c("1", "2", "NULL"))) test.as.vector.375 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "list"), identicalTo(list(1L, 2L, NULL))) test.as.vector.376 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "expression"), deparsesTo("expression(1L, 2L, NULL)")) test.as.vector.377 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = "rubish"), throwsError()) test.as.vector.378 <- function() assertThat(as.vector(list(1L, 2L, NULL), mode = NA_character_), throwsError()) test.as.vector.379 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "any"), identicalTo(list(1, 2, list(3, 4)))) test.as.vector.380 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "logical"), throwsError()) test.as.vector.381 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "integer"), throwsError()) test.as.vector.382 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "numeric"), throwsError()) test.as.vector.383 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "double"), throwsError()) test.as.vector.384 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "complex"), throwsError()) test.as.vector.385 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "raw"), throwsError()) test.as.vector.386 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "character"), identicalTo(c("1", "2", "list(3, 4)"))) test.as.vector.387 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "list"), identicalTo(list(1, 2, list(3, 4)))) test.as.vector.388 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "expression"), deparsesTo("expression(1, 2, list(3, 4))")) test.as.vector.389 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = "rubish"), throwsError()) test.as.vector.390 <- function() assertThat(as.vector(list(1, 2, list(3, 4)), mode = NA_character_), throwsError()) test.as.vector.391 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "any"), identicalTo(list(1, 2, numeric(0)))) test.as.vector.392 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "logical"), identicalTo(c(TRUE, TRUE, NA))) test.as.vector.393 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "integer"), identicalTo(c(1L, 2L, NA))) test.as.vector.394 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "numeric"), identicalTo(c(1, 2, NA))) test.as.vector.395 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "double"), identicalTo(c(1, 2, NA))) test.as.vector.396 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "complex"), identicalTo(c(1+0i, 2+0i, NA))) test.as.vector.397 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x00)))) test.as.vector.398 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "character"), identicalTo(c("1", "2", "numeric(0)"))) test.as.vector.399 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "list"), identicalTo(list(1, 2, numeric(0)))) test.as.vector.400 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "expression"), deparsesTo("expression(1, 2, numeric(0))")) test.as.vector.401 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = "rubish"), throwsError()) test.as.vector.402 <- function() assertThat(as.vector(list(1, 2, numeric(0)), mode = NA_character_), throwsError()) test.as.vector.403 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "any"), identicalTo(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))))) test.as.vector.404 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "logical"), throwsError()) test.as.vector.405 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "integer"), throwsError()) test.as.vector.406 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "numeric"), throwsError()) test.as.vector.407 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "double"), throwsError()) test.as.vector.408 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "complex"), throwsError()) test.as.vector.409 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "raw"), throwsError()) test.as.vector.410 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "character"), identicalTo(c("3", "a", "list(\"b\", z = list(TRUE, \"c\"))"))) test.as.vector.411 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "list"), identicalTo(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))))) test.as.vector.412 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "expression"), deparsesTo("expression(3, \"a\", list(\"b\", z = list(TRUE, \"c\")))")) test.as.vector.413 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = "rubish"), throwsError()) test.as.vector.414 <- function() assertThat(as.vector(list(3, "a", structure(list("b", z = list(TRUE, "c")), .Names = c("", "z"))), mode = NA_character_), throwsError()) test.as.vector.415 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "any"), identicalTo(structure(list("NA" = 1, 2, b = 3), .Names = c(NA, "", "b")))) test.as.vector.416 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE))) test.as.vector.417 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "integer"), identicalTo(1:3)) test.as.vector.418 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "numeric"), identicalTo(c(1, 2, 3))) test.as.vector.419 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "double"), identicalTo(c(1, 2, 3))) test.as.vector.420 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i))) test.as.vector.421 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03)))) test.as.vector.422 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "character"), identicalTo(c("1", "2", "3"))) test.as.vector.423 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "list"), identicalTo(structure(list("NA" = 1, 2, b = 3), .Names = c(NA, "", "b")))) test.as.vector.424 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "expression"), deparsesTo("structure(expression(`NA` = 1, 2, b = 3), .Names = c(NA, \"\", \"b\"))")) test.as.vector.425 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = "rubish"), throwsError()) test.as.vector.426 <- function() assertThat(as.vector(structure(list(`NA` = 1, 2, b = 3), .Names = c(NA, "", "b")), mode = NA_character_), throwsError()) test.as.vector.427 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "any"), identicalTo(pairlist(41, "a", 21L))) test.as.vector.428 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "logical"), identicalTo(c(TRUE, NA, TRUE))) test.as.vector.429 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "integer"), identicalTo(c(41L, NA, 21L))) test.as.vector.430 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "numeric"), identicalTo(c(41, NA, 21))) test.as.vector.431 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "double"), identicalTo(c(41, NA, 21))) test.as.vector.432 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "complex"), identicalTo(c(41+0i, NA, 21+0i))) test.as.vector.433 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "raw"), identicalTo(as.raw(c(0x29, 0x00, 0x15)))) test.as.vector.434 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "character"), identicalTo(c("41", "a", "21"))) test.as.vector.435 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "list"), identicalTo(list(41, "a", 21L))) test.as.vector.436 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "expression"), deparsesTo("expression(pairlist(41, \"a\", 21L))")) test.as.vector.437 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = "rubish"), throwsError()) test.as.vector.438 <- function() assertThat(as.vector(pairlist(41, "a", 21L), mode = NA_character_), throwsError()) test.as.vector.439 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "any"), identicalTo(pairlist(a = 41, 42))) test.as.vector.440 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "logical"), identicalTo(c(TRUE, TRUE))) test.as.vector.441 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "integer"), identicalTo(41:42)) test.as.vector.442 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "numeric"), identicalTo(c(41, 42))) test.as.vector.443 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "double"), identicalTo(c(41, 42))) test.as.vector.444 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "complex"), identicalTo(c(41+0i, 42+0i))) test.as.vector.445 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "raw"), identicalTo(as.raw(c(0x29, 0x2a)))) test.as.vector.446 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "character"), identicalTo(c("41", "42"))) test.as.vector.447 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "list"), identicalTo(structure(list(a = 41, 42), .Names = c("a", "")))) test.as.vector.448 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "expression"), deparsesTo("expression(pairlist(a = 41, 42))")) test.as.vector.449 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = "rubish"), throwsError()) test.as.vector.450 <- function() assertThat(as.vector(pairlist(a = 41, 42), mode = NA_character_), throwsError()) test.as.vector.451 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "any"), identicalTo(pairlist(a = 41, NULL))) test.as.vector.452 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "logical"), throwsError()) test.as.vector.453 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "integer"), throwsError()) test.as.vector.454 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "numeric"), throwsError()) test.as.vector.455 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "double"), throwsError()) test.as.vector.456 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "complex"), throwsError()) test.as.vector.457 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "raw"), throwsError()) test.as.vector.458 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "character"), identicalTo(c("41", "NULL"))) test.as.vector.459 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "list"), identicalTo(structure(list(a = 41, NULL), .Names = c("a", "")))) test.as.vector.460 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "expression"), deparsesTo("expression(pairlist(a = 41, NULL))")) test.as.vector.461 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = "rubish"), throwsError()) test.as.vector.462 <- function() assertThat(as.vector(pairlist(a = 41, NULL), mode = NA_character_), throwsError()) test.as.vector.463 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "any"), identicalTo(1:12)) test.as.vector.464 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE))) test.as.vector.465 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "integer"), identicalTo(1:12)) test.as.vector.466 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "numeric"), identicalTo(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))) test.as.vector.467 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "double"), identicalTo(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))) test.as.vector.468 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i, 4+0i, 5+0i, 6+0i, 7+0i, 8+0i, 9+0i, 10+0i, 11+0i, 12+0i))) test.as.vector.469 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c)))) test.as.vector.470 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "character"), identicalTo(c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))) test.as.vector.471 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "list"), identicalTo(list(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L))) test.as.vector.472 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "expression"), deparsesTo("expression(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L)")) test.as.vector.473 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = "rubish"), throwsError()) test.as.vector.474 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4), mode = NA_character_), throwsError()) test.as.vector.475 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "any"), identicalTo(1:12)) test.as.vector.476 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE, TRUE))) test.as.vector.477 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "integer"), identicalTo(1:12)) test.as.vector.478 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "numeric"), identicalTo(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))) test.as.vector.479 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "double"), identicalTo(c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12))) test.as.vector.480 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i, 4+0i, 5+0i, 6+0i, 7+0i, 8+0i, 9+0i, 10+0i, 11+0i, 12+0i))) test.as.vector.481 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c)))) test.as.vector.482 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "character"), identicalTo(c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"))) test.as.vector.483 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "list"), identicalTo(list(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L))) test.as.vector.484 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "expression"), deparsesTo("expression(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 11L, 12L)")) test.as.vector.485 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = "rubish"), throwsError()) test.as.vector.486 <- function() assertThat(as.vector(structure(1:12, .Dim = 3:4, .Dimnames = structure(list( x = c("a", "b", "c"), y = c("d", "e", "f", "g")), .Names = c("x", "y"))), mode = NA_character_), throwsError()) test.as.vector.487 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "any"), identicalTo(1:3)) test.as.vector.488 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE))) test.as.vector.489 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "integer"), identicalTo(1:3)) test.as.vector.490 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "numeric"), identicalTo(c(1, 2, 3))) test.as.vector.491 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "double"), identicalTo(c(1, 2, 3))) test.as.vector.492 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i))) test.as.vector.493 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03)))) test.as.vector.494 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "character"), identicalTo(c("1", "2", "3"))) test.as.vector.495 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "list"), identicalTo(list(1L, 2L, 3L))) test.as.vector.496 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "expression"), deparsesTo("expression(1L, 2L, 3L)")) test.as.vector.497 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = "rubish"), throwsError()) test.as.vector.498 <- function() assertThat(as.vector(structure(1:3, rando.attrib = 941L), mode = NA_character_), throwsError()) test.as.vector.499 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "any"), identicalTo(1:3)) test.as.vector.500 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE))) test.as.vector.501 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "integer"), identicalTo(1:3)) test.as.vector.502 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "numeric"), identicalTo(c(1, 2, 3))) test.as.vector.503 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "double"), identicalTo(c(1, 2, 3))) test.as.vector.504 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i))) test.as.vector.505 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03)))) test.as.vector.506 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "character"), identicalTo(c("1", "2", "3"))) test.as.vector.507 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "list"), identicalTo(structure(list(a = 1L, b = 2L, c = 3L), .Names = c("a", "b", "c")))) test.as.vector.508 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "expression"), deparsesTo("expression(1L, 2L, 3L)")) test.as.vector.509 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = "rubish"), throwsError()) test.as.vector.510 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = list(c("a", "b", "c"))), mode = NA_character_), throwsError()) test.as.vector.511 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "any"), identicalTo(1:3)) test.as.vector.512 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "logical"), identicalTo(c(TRUE, TRUE, TRUE))) test.as.vector.513 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "integer"), identicalTo(1:3)) test.as.vector.514 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "numeric"), identicalTo(c(1, 2, 3))) test.as.vector.515 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "double"), identicalTo(c(1, 2, 3))) test.as.vector.516 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "complex"), identicalTo(c(1+0i, 2+0i, 3+0i))) test.as.vector.517 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "raw"), identicalTo(as.raw(c(0x01, 0x02, 0x03)))) test.as.vector.518 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "character"), identicalTo(c("1", "2", "3"))) test.as.vector.519 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "list"), identicalTo(structure(list(a = 1L, b = 2L, c = 3L), .Names = c("a", "b", "c")))) test.as.vector.520 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "expression"), deparsesTo("expression(1L, 2L, 3L)")) test.as.vector.521 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = "rubish"), throwsError()) test.as.vector.522 <- function() assertThat(as.vector(structure(1:3, .Dim = 3L, .Dimnames = structure(list( z = c("a", "b", "c")), .Names = "z")), mode = NA_character_), throwsError()) test.as.vector.523 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "any"), identicalTo(99)) test.as.vector.524 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "logical"), identicalTo(99)) test.as.vector.525 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "integer"), identicalTo(99)) test.as.vector.526 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "numeric"), identicalTo(99)) test.as.vector.527 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "double"), identicalTo(99)) test.as.vector.528 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "complex"), identicalTo(99)) test.as.vector.529 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "raw"), identicalTo(99)) test.as.vector.530 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "character"), identicalTo(99)) test.as.vector.531 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "list"), identicalTo(99)) test.as.vector.532 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "expression"), identicalTo(99)) test.as.vector.533 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = "rubish"), identicalTo(99)) test.as.vector.534 <- function() assertThat(as.vector(structure(list("foo"), class = "foo"), mode = NA_character_), identicalTo(99)) test.as.vector.535 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "any"), identicalTo(99)) test.as.vector.536 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "logical"), identicalTo(99)) test.as.vector.537 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "integer"), identicalTo(99)) test.as.vector.538 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "numeric"), identicalTo(99)) test.as.vector.539 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "double"), identicalTo(99)) test.as.vector.540 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "complex"), identicalTo(99)) test.as.vector.541 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "raw"), identicalTo(99)) test.as.vector.542 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "character"), identicalTo(99)) test.as.vector.543 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "list"), identicalTo(99)) test.as.vector.544 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "expression"), identicalTo(99)) test.as.vector.545 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = "rubish"), identicalTo(99)) test.as.vector.546 <- function() assertThat(as.vector(structure(list("bar"), class = "foo"), mode = NA_character_), identicalTo(99)) test.as.vector.547 <- function() assertThat(as.vector(quote(xyz), mode = "any"), throwsError()) test.as.vector.548 <- function() assertThat(as.vector(quote(xyz), mode = "logical"), throwsError()) test.as.vector.549 <- function() assertThat(as.vector(quote(xyz), mode = "integer"), throwsError()) test.as.vector.550 <- function() assertThat(as.vector(quote(xyz), mode = "numeric"), throwsError()) test.as.vector.551 <- function() assertThat(as.vector(quote(xyz), mode = "double"), throwsError()) test.as.vector.552 <- function() assertThat(as.vector(quote(xyz), mode = "complex"), throwsError()) test.as.vector.553 <- function() assertThat(as.vector(quote(xyz), mode = "raw"), throwsError()) test.as.vector.554 <- function() assertThat(as.vector(quote(xyz), mode = "character"), identicalTo("xyz")) test.as.vector.555 <- function() assertThat(as.vector(quote(xyz), mode = "list"), identicalTo(list(quote(xyz)))) test.as.vector.556 <- function() assertThat(as.vector(quote(xyz), mode = "expression"), deparsesTo("expression(xyz)")) test.as.vector.557 <- function() assertThat(as.vector(quote(xyz), mode = "rubish"), throwsError()) test.as.vector.558 <- function() assertThat(as.vector(quote(xyz), mode = NA_character_), throwsError()) test.as.vector.559 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "any"), deparsesTo("sin(3.14)")) test.as.vector.560 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "logical"), throwsError()) test.as.vector.561 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "integer"), throwsError()) test.as.vector.562 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "numeric"), throwsError()) test.as.vector.563 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "double"), throwsError()) test.as.vector.564 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "complex"), throwsError()) test.as.vector.565 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "raw"), throwsError()) test.as.vector.566 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "character"), identicalTo(c("sin", "3.14"))) test.as.vector.567 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "list"), identicalTo(list(quote(sin), 3.14))) test.as.vector.568 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "expression"), deparsesTo("expression(sin(3.14))")) test.as.vector.569 <- function() assertThat(as.vector(quote(sin(3.14)), mode = "rubish"), throwsError()) test.as.vector.570 <- function() assertThat(as.vector(quote(sin(3.14)), mode = NA_character_), throwsError()) test.as.vector.571 <- function() assertThat(as.vector("NaN", mode = "any"), identicalTo("NaN")) test.as.vector.572 <- function() assertThat(as.vector("NaN", mode = "logical"), identicalTo(NA)) test.as.vector.573 <- function() assertThat(as.vector("NaN", mode = "integer"), identicalTo(NA_integer_)) test.as.vector.574 <- function() assertThat(as.vector("NaN", mode = "numeric"), identicalTo(NaN)) test.as.vector.575 <- function() assertThat(as.vector("NaN", mode = "double"), identicalTo(NaN)) test.as.vector.576 <- function() assertThat(as.vector("NaN", mode = "complex"), identicalTo(complex(real=NaN, imaginary=0))) test.as.vector.577 <- function() assertThat(as.vector("NaN", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.578 <- function() assertThat(as.vector("NaN", mode = "character"), identicalTo("NaN")) test.as.vector.579 <- function() assertThat(as.vector("NaN", mode = "list"), identicalTo(list("NaN"))) test.as.vector.580 <- function() assertThat(as.vector("NaN", mode = "expression"), deparsesTo("expression(\"NaN\")")) test.as.vector.581 <- function() assertThat(as.vector("NaN", mode = "rubish"), throwsError()) test.as.vector.582 <- function() assertThat(as.vector("NaN", mode = NA_character_), throwsError()) test.as.vector.583 <- function() assertThat(as.vector("NABOOM!", mode = "any"), identicalTo("NABOOM!")) test.as.vector.584 <- function() assertThat(as.vector("NABOOM!", mode = "logical"), identicalTo(NA)) test.as.vector.585 <- function() assertThat(as.vector("NABOOM!", mode = "integer"), identicalTo(NA_integer_)) test.as.vector.586 <- function() assertThat(as.vector("NABOOM!", mode = "numeric"), identicalTo(NA_real_)) test.as.vector.587 <- function() assertThat(as.vector("NABOOM!", mode = "double"), identicalTo(NA_real_)) test.as.vector.588 <- function() assertThat(as.vector("NABOOM!", mode = "complex"), identicalTo(NA_complex_)) test.as.vector.589 <- function() assertThat(as.vector("NABOOM!", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.590 <- function() assertThat(as.vector("NABOOM!", mode = "character"), identicalTo("NABOOM!")) test.as.vector.591 <- function() assertThat(as.vector("NABOOM!", mode = "list"), identicalTo(list("NABOOM!"))) test.as.vector.592 <- function() assertThat(as.vector("NABOOM!", mode = "expression"), deparsesTo("expression(\"NABOOM!\")")) test.as.vector.593 <- function() assertThat(as.vector("NABOOM!", mode = "rubish"), throwsError()) test.as.vector.594 <- function() assertThat(as.vector("NABOOM!", mode = NA_character_), throwsError()) test.as.vector.595 <- function() assertThat(as.vector("NaNaNabooboo", mode = "any"), identicalTo("NaNaNabooboo")) test.as.vector.596 <- function() assertThat(as.vector("NaNaNabooboo", mode = "logical"), identicalTo(NA)) test.as.vector.597 <- function() assertThat(as.vector("NaNaNabooboo", mode = "integer"), identicalTo(NA_integer_)) test.as.vector.598 <- function() assertThat(as.vector("NaNaNabooboo", mode = "numeric"), identicalTo(NA_real_)) test.as.vector.599 <- function() assertThat(as.vector("NaNaNabooboo", mode = "double"), identicalTo(NA_real_)) test.as.vector.600 <- function() assertThat(as.vector("NaNaNabooboo", mode = "complex"), identicalTo(NA_complex_)) test.as.vector.601 <- function() assertThat(as.vector("NaNaNabooboo", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.602 <- function() assertThat(as.vector("NaNaNabooboo", mode = "character"), identicalTo("NaNaNabooboo")) test.as.vector.603 <- function() assertThat(as.vector("NaNaNabooboo", mode = "list"), identicalTo(list("NaNaNabooboo"))) test.as.vector.604 <- function() assertThat(as.vector("NaNaNabooboo", mode = "expression"), deparsesTo("expression(\"NaNaNabooboo\")")) test.as.vector.605 <- function() assertThat(as.vector("NaNaNabooboo", mode = "rubish"), throwsError()) test.as.vector.606 <- function() assertThat(as.vector("NaNaNabooboo", mode = NA_character_), throwsError()) test.as.vector.607 <- function() assertThat(as.vector("-Inf", mode = "any"), identicalTo("-Inf")) test.as.vector.608 <- function() assertThat(as.vector("-Inf", mode = "logical"), identicalTo(NA)) test.as.vector.609 <- function() assertThat(as.vector("-Inf", mode = "integer"), identicalTo(NA_integer_)) test.as.vector.610 <- function() assertThat(as.vector("-Inf", mode = "numeric"), identicalTo(-Inf)) test.as.vector.611 <- function() assertThat(as.vector("-Inf", mode = "double"), identicalTo(-Inf)) test.as.vector.612 <- function() assertThat(as.vector("-Inf", mode = "complex"), identicalTo(-Inf+0i)) test.as.vector.613 <- function() assertThat(as.vector("-Inf", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.614 <- function() assertThat(as.vector("-Inf", mode = "character"), identicalTo("-Inf")) test.as.vector.615 <- function() assertThat(as.vector("-Inf", mode = "list"), identicalTo(list("-Inf"))) test.as.vector.616 <- function() assertThat(as.vector("-Inf", mode = "expression"), deparsesTo("expression(\"-Inf\")")) test.as.vector.617 <- function() assertThat(as.vector("-Inf", mode = "rubish"), throwsError()) test.as.vector.618 <- function() assertThat(as.vector("-Inf", mode = NA_character_), throwsError()) test.as.vector.619 <- function() assertThat(as.vector("+Infinity", mode = "any"), identicalTo("+Infinity")) test.as.vector.620 <- function() assertThat(as.vector("+Infinity", mode = "logical"), identicalTo(NA)) test.as.vector.621 <- function() assertThat(as.vector("+Infinity", mode = "integer"), identicalTo(NA_integer_)) test.as.vector.622 <- function() assertThat(as.vector("+Infinity", mode = "numeric"), identicalTo(Inf)) test.as.vector.623 <- function() assertThat(as.vector("+Infinity", mode = "double"), identicalTo(Inf)) test.as.vector.624 <- function() assertThat(as.vector("+Infinity", mode = "complex"), identicalTo(Inf+0i)) test.as.vector.625 <- function() assertThat(as.vector("+Infinity", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.626 <- function() assertThat(as.vector("+Infinity", mode = "character"), identicalTo("+Infinity")) test.as.vector.627 <- function() assertThat(as.vector("+Infinity", mode = "list"), identicalTo(list("+Infinity"))) test.as.vector.628 <- function() assertThat(as.vector("+Infinity", mode = "expression"), deparsesTo("expression(\"+Infinity\")")) test.as.vector.629 <- function() assertThat(as.vector("+Infinity", mode = "rubish"), throwsError()) test.as.vector.630 <- function() assertThat(as.vector("+Infinity", mode = NA_character_), throwsError()) test.as.vector.631 <- function() assertThat(as.vector("Infinity and beyond!", mode = "any"), identicalTo("Infinity and beyond!")) test.as.vector.632 <- function() assertThat(as.vector("Infinity and beyond!", mode = "logical"), identicalTo(NA)) test.as.vector.633 <- function() assertThat(as.vector("Infinity and beyond!", mode = "integer"), identicalTo(NA_integer_)) test.as.vector.634 <- function() assertThat(as.vector("Infinity and beyond!", mode = "numeric"), identicalTo(NA_real_)) test.as.vector.635 <- function() assertThat(as.vector("Infinity and beyond!", mode = "double"), identicalTo(NA_real_)) test.as.vector.636 <- function() assertThat(as.vector("Infinity and beyond!", mode = "complex"), identicalTo(NA_complex_)) test.as.vector.637 <- function() assertThat(as.vector("Infinity and beyond!", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.638 <- function() assertThat(as.vector("Infinity and beyond!", mode = "character"), identicalTo("Infinity and beyond!")) test.as.vector.639 <- function() assertThat(as.vector("Infinity and beyond!", mode = "list"), identicalTo(list("Infinity and beyond!"))) test.as.vector.640 <- function() assertThat(as.vector("Infinity and beyond!", mode = "expression"), deparsesTo("expression(\"Infinity and beyond!\")")) test.as.vector.641 <- function() assertThat(as.vector("Infinity and beyond!", mode = "rubish"), throwsError()) test.as.vector.642 <- function() assertThat(as.vector("Infinity and beyond!", mode = NA_character_), throwsError()) test.as.vector.643 <- function() assertThat(as.vector("Infi", mode = "any"), identicalTo("Infi")) test.as.vector.644 <- function() assertThat(as.vector("Infi", mode = "logical"), identicalTo(NA)) test.as.vector.645 <- function() assertThat(as.vector("Infi", mode = "integer"), identicalTo(NA_integer_)) test.as.vector.646 <- function() assertThat(as.vector("Infi", mode = "numeric"), identicalTo(NA_real_)) test.as.vector.647 <- function() assertThat(as.vector("Infi", mode = "double"), identicalTo(NA_real_)) test.as.vector.648 <- function() assertThat(as.vector("Infi", mode = "complex"), identicalTo(NA_complex_)) test.as.vector.649 <- function() assertThat(as.vector("Infi", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.650 <- function() assertThat(as.vector("Infi", mode = "character"), identicalTo("Infi")) test.as.vector.651 <- function() assertThat(as.vector("Infi", mode = "list"), identicalTo(list("Infi"))) test.as.vector.652 <- function() assertThat(as.vector("Infi", mode = "expression"), deparsesTo("expression(\"Infi\")")) test.as.vector.653 <- function() assertThat(as.vector("Infi", mode = "rubish"), throwsError()) test.as.vector.654 <- function() assertThat(as.vector("Infi", mode = NA_character_), throwsError()) test.as.vector.655 <- function() assertThat(as.vector("0.03f", mode = "any"), identicalTo("0.03f")) test.as.vector.656 <- function() assertThat(as.vector("0.03f", mode = "logical"), identicalTo(NA)) test.as.vector.657 <- function() assertThat(as.vector("0.03f", mode = "integer"), identicalTo(NA_integer_)) test.as.vector.658 <- function() assertThat(as.vector("0.03f", mode = "numeric"), identicalTo(NA_real_)) test.as.vector.659 <- function() assertThat(as.vector("0.03f", mode = "double"), identicalTo(NA_real_)) test.as.vector.660 <- function() assertThat(as.vector("0.03f", mode = "complex"), identicalTo(NA_complex_)) test.as.vector.661 <- function() assertThat(as.vector("0.03f", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.662 <- function() assertThat(as.vector("0.03f", mode = "character"), identicalTo("0.03f")) test.as.vector.663 <- function() assertThat(as.vector("0.03f", mode = "list"), identicalTo(list("0.03f"))) test.as.vector.664 <- function() assertThat(as.vector("0.03f", mode = "expression"), deparsesTo("expression(\"0.03f\")")) test.as.vector.665 <- function() assertThat(as.vector("0.03f", mode = "rubish"), throwsError()) test.as.vector.666 <- function() assertThat(as.vector("0.03f", mode = NA_character_), throwsError()) test.as.vector.667 <- function() assertThat(as.vector(" 0.0330 ", mode = "any"), identicalTo(" 0.0330 ")) test.as.vector.668 <- function() assertThat(as.vector(" 0.0330 ", mode = "logical"), identicalTo(NA)) test.as.vector.669 <- function() assertThat(as.vector(" 0.0330 ", mode = "integer"), identicalTo(0L)) test.as.vector.670 <- function() assertThat(as.vector(" 0.0330 ", mode = "numeric"), identicalTo(0.033, tol = 0.000100)) test.as.vector.671 <- function() assertThat(as.vector(" 0.0330 ", mode = "double"), identicalTo(0.033, tol = 0.000100)) test.as.vector.672 <- function() assertThat(as.vector(" 0.0330 ", mode = "complex"), identicalTo(0.033+0i)) test.as.vector.673 <- function() assertThat(as.vector(" 0.0330 ", mode = "raw"), identicalTo(as.raw(0x00))) test.as.vector.674 <- function() assertThat(as.vector(" 0.0330 ", mode = "character"), identicalTo(" 0.0330 ")) test.as.vector.675 <- function() assertThat(as.vector(" 0.0330 ", mode = "list"), identicalTo(list(" 0.0330 "))) test.as.vector.676 <- function() assertThat(as.vector(" 0.0330 ", mode = "expression"), deparsesTo("expression(\" 0.0330 \")")) test.as.vector.677 <- function() assertThat(as.vector(" 0.0330 ", mode = "rubish"), throwsError()) test.as.vector.678 <- function() assertThat(as.vector(" 0.0330 ", mode = NA_character_), throwsError())
glmdev <- function(y, ni, ci, wa, vtheta, offset=0, icase = .dFvGet()$ics) { if(missing(y)) messagena("y") n <- length(y) if(missing(ni)) ni <- integer(n) if(missing(ci)) messagena("ci") if(missing(wa)) messagena("wa") if(missing(vtheta)) messagena("vtheta") if (length(offset)==1) offset <- rep(0,n) dev <- double(1) thetas <- double(n) li <- double(n) sc <- double(n) f.res <- .Fortran("glmdevz", y = to.single(y), ni = to.integer(ni), ci = to.single(ci), wa = to.single(wa), vtheta = to.single(vtheta), oi = to.single(offset), n = to.integer(n), icase = to.integer(icase), dev = to.double(dev), thetas = to.double(thetas), li = to.double(li), sc = to.double(sc)) sc <- f.res$sc list(dev = f.res$dev, thetas = f.res$thetas, li = f.res$li, sc = sc) }
contour.RVineMatrix <- function(x, tree = "ALL", xylim = NULL, cex.nums = 1, data = NULL, ...) { d <- nrow(x$Matrix) if (all(tree == "ALL")) tree <- seq.int(d-1) n.tree <- length(tree) if (!is.null(list(...)$type)) stop("Only contour plots allowed. Don't use the type argument!") usr <- par(mfrow = c(n.tree, d - min(tree)), mar = rep(0, 4)) on.exit(par(usr)) psobs <- if (!is.null(data)) vine_psobs(data, x) else NULL TUMblue <- rgb(0, 103/255, 198/255) tint.seq <- seq(0.5, 0.5, length.out = d - 1) clrs <- rev(sapply(tint.seq, function(x) tint(TUMblue, x, 0.7))) if (!is.null(list(...)$margins)) { margins <- list(...)$margins if (!(margins %in% c("norm", "unif", "exp", "flexp"))) contour(BiCop(0), margins = c(0, 10)) } else { margins <- "norm" } if (is.null(xylim)) xylim <- switch(margins, "norm" = c(-3, 3), "unif" = c(0, 1 - 1e-2), "exp" = c(0, 10), "flexp" = c(-10, 0)) xlim <- ylim <- xylim offs <- 0.25 mult <- 1.35 ylim[2] <- ylim[2] + offs*diff(ylim) cnt <- 0 k <- d e <- numeric(0) class(e) <- "try-error" while ("try-error" %in% class(e)) { e <- try({ maxnums <- get_num(1, tree = max(tree), RVM = x) for (i in rev(tree)) { for (j in 1:(d - min(tree))) { if (j <= d - i) { if (is.null(psobs)) { pcfit <- BiCop(family = x$family[d - i + 1, j], par = x$par[d - i + 1, j], par2 = x$par2[d - i + 1, j], check.pars = FALSE) } else { pcfit <- kdecopula::kdecop(psobs[[i]][[j]]) } args <- list(x = pcfit, drawlabels = FALSE, xlab = "", ylab = "", xlim = xlim, ylim = ylim, xaxt = "n", yaxt = "n", add = TRUE) plot.new() plot.window(xlim = xlim, ylim = ylim, xaxs = "i", yaxs = "i") do.call(contour, modifyList(args, list(...))) abline(h = ylim[2] - diff(ylim)/mult*offs) ci <- min(length(clrs) + 1 - i, 10) polygon(x = c(xlim[1] - diff(xlim), xlim[1] - diff(xlim), xlim[2] + diff(xlim), xlim[2] + diff(xlim)), y = c(ylim[2] + diff(ylim)/mult*offs, ylim[2] - diff(ylim)/mult*offs, ylim[2] - diff(ylim)/mult*offs, ylim[2] + diff(ylim)/mult*offs), col = clrs[ci]) abline(v = xlim) abline(h = ylim) cx1 <- 0.75 * diff(xlim) / strwidth(maxnums) ty <- ylim[2] - diff(ylim)/mult*offs cx2 <- 0.75 * (ylim[2] - ty) / strheight(maxnums) cx <- min(cx1, cx2) text(x = sum(xlim)/2, y = ty + 0.225 / cex.nums * (ylim[2] - ty), cex = cex.nums * cx, labels = get_num(j, tree = i, RVM = x), pos = 3, offset = 0) } else { plot.new() } } } } , silent = TRUE) if (length(tree) < 1) stop("Error in plot.new() : figure margins too large") if ("try-error" %in% class(e)) { cnt <- cnt + 1 tree <- tree[-which(tree == max(tree))] par(mfrow = c(n.tree - cnt, d - min(tree))) } } if (length(tree) != n.tree) { nmbr.msg <- as.character(tree[1]) if (length(tree) > 2) { for (i in tree[-c(1, length(tree))]) { nmbr.msg <- paste(nmbr.msg, i, sep=", ") } } if (length(tree) > 1) { s.msg <- "s " nmbr.msg <- paste(nmbr.msg, "and", tree[length(tree)], "were plotted. ") } else { s.msg <- " " nmbr.msg <- paste(nmbr.msg, "was plotted. ", sep=" ") } msg.space <- "There is not enough space." msg.tree <- paste("Only Tree", s.msg, nmbr.msg, "Use the 'tree' argument or enlarge figure margins", " to see the others.", sep = "") message(paste(msg.space, msg.tree)) } } vine_psobs <- function (uev, object) { uev <- as.matrix(uev) if (ncol(uev) == 1) uev <- matrix(uev, 1, nrow(uev)) if (any(uev > 1) || any(uev < 0)) stop("Data has be in the interval [0,1].") n <- ncol(uev) N <- nrow(uev) if (ncol(uev) != ncol(object$Matrix)) stop("Dimensions of 'data' and 'object' do not match.") if (!is(object,"RVineMatrix")) stop("'object' has to be an RVineMatrix object") o <- diag(object$Matrix) oldobject <- object if (any(o != length(o):1)) { object <- normalizeRVineMatrix(object) uev <- matrix(uev[, o[length(o):1]], N, n) } CondDistr <- neededCondDistr(object$Matrix) val <- array(1, dim = c(n, n, N)) out <- lapply(1:(n - 1), list) V <- list() V$direct <- array(NA, dim = c(n, n, N)) V$indirect <- array(NA, dim = c(n, n, N)) V$direct[n, , ] <- t(uev[, n:1]) for (i in (n - 1):1) { for (k in n:(i + 1)) { m <- object$MaxMat[k, i] zr1 <- V$direct[k, i, ] if (m == object$Matrix[k, i]) { zr2 <- V$direct[k, (n - m + 1), ] } else { zr2 <- V$indirect[k, (n - m + 1), ] } out[[n - k + 1]][[i]] <- cbind(zr2, zr1) if (CondDistr$direct[k - 1, i]) V$direct[k - 1, i, ] <- BiCopHfunc1(zr2, zr1, object$family[k, i], object$par[k, i], object$par2[k, i], check.pars = FALSE) if (CondDistr$indirect[k - 1, i]) V$indirect[k - 1, i, ] <- BiCopHfunc2(zr2, zr1, object$family[k, i], object$par[k, i], object$par2[k, i], check.pars = FALSE) } } out }
cvi_evaluators <- function(type = "valid", fuzzy = FALSE, ground.truth = NULL) { if (fuzzy) { external <- c("RI", "ARI", "VI", "NMIM") internal <- c("MPC", "K", "T", "SC", "PBMF") minimize <- c("VI", "K", "T") } else { external <- c("RI", "ARI", "J", "FM", "VI") internal <- c("Sil", "D", "COP", "DB", "DBstar", "CH", "SF") minimize <- c("VI", "COP", "DB", "DBstar") } if ("valid" %in% type) { type <- if (is.null(ground.truth)) internal else c(external, internal) } else if ("external" %in% type) { if (is.null(ground.truth)) stop("The ground.truth is needed for external CVIs.") type <- external } else if ("internal" %in% type) { type <- internal } else { type <- match.arg(type, c(external, internal), several.ok = TRUE) if (any(external %in% type) && is.null(ground.truth)) stop("The ground.truth is needed for external CVIs.") } majority <- function(x) { ux <- unique(x) ux[which.max(tabulate(match(x, ux)))] } score <- function(objs, ...) { do.call(rbind, lapply(objs, function(obj) { internal <- intersect(type, internal) external <- intersect(type, external) if (length(internal) > 0L) cvis <- cvi(a = obj, type = internal, ...) else cvis <- numeric() if (length(external) > 0L) { if (fuzzy) cvis <- c(cvis, cvi(obj@fcluster, ground.truth, external, ...)) else cvis <- c(cvis, cvi(obj@cluster, ground.truth, external, ...)) } minimized <- names(cvis) %in% minimize if (length(minimized) > 0L && any(minimized)) cvis[minimized] <- 1 / cvis[minimized] cvis })) } pick <- function(results, objs, ...) { objs_missing <- missing(objs) best_by_type <- sapply(results, function(result) { score <- result[type] best_by_cvi <- apply(score, 2L, which.max) if (length(type) > 1L && length(unique(best_by_cvi)) == length(best_by_cvi)) stop("All votes are distinct, so majority voting is inconclusive.") majority(best_by_cvi) }) best_overall <- Map(results, best_by_type, f = function(result, row_id) { result[row_id, type, drop = FALSE] }) best_overall <- do.call(rbind, best_overall) best_overall <- apply(best_overall, 2L, which.max) if (length(type) > 1L && length(unique(best_overall)) == length(best_overall)) stop("All votes are distinct, so majority voting is inconclusive.") best_overall <- majority(best_overall) if (objs_missing) results[[best_overall]][best_by_type[best_overall], , drop = FALSE] else list( object = objs[[best_overall]][[best_by_type[best_overall]]], config = results[[best_overall]][best_by_type[best_overall], , drop = FALSE] ) } list(score = score, pick = pick) }
"mahasuhab" <- function(x, pts, type=c("distance", "probability")) { type<-match.arg(type) if (!inherits(x, "SpatialPixelsDataFrame")) stop("should be an object of class SpatialPixelsDataFrame") gridded(x) <- TRUE gr <- gridparameters(x) if (nrow(gr) > 2) stop("x should be defined in two dimensions") if ((gr[1, 2] - gr[2, 2])> get(".adeoptions", envir=.adehabitatMAEnv)$epsilon) stop("the cellsize should be the same in x and y directions") if (!inherits(pts, "SpatialPoints")) stop("should inherit from class \"SpatialPoints\"") hihi<-join(pts, x) hihi <- hihi[!is.na(hihi[,1]),] used<-list() for (i in 1:ncol(hihi)) { if (is.factor(hihi[,i])) used[[i]]<-acm.disjonctif(data.frame(hihi[,i]))[,-1] else used[[i]]<-hihi[,i] } used[[i+1]]<-rep(1, nrow(hihi)) hihi<-as.data.frame(used) hihi<-hihi[!is.na(hihi[,1]),] mu<-apply(hihi,2, function(x) mean(x, na.rm=TRUE)) varcov<-t(as.matrix(hihi))%*%as.matrix(hihi)/nrow(hihi) kasc <- slot(x,"data") ava<-list() for (i in 1:ncol(kasc)) { if (is.factor(kasc[,i])) ava[[i]]<-acm.disjonctif(data.frame(kasc[,i]))[,-1] else ava[[i]]<-kasc[,i] } ava[[i+1]]<-rep(1, nrow(kasc)) df<-as.data.frame(ava) map<-mahalanobis(as.matrix(df), mu, varcov) if (type=="probability") map<-1-pchisq(map, ncol(hihi)-1) map <- data.frame(MD=map) coordinates(map) <- coordinates(x) gridded(map) <- TRUE return(map) }
curvep_defaults <- function() { defaults <- list( TRSH = 15, RNGE = -1000000, MXDV = 5, CARR = 0, BSFT = 3, USHP = 4, TrustHi = TRUE, StrictImp = TRUE, DUMV = -999, TLOG = -24, seed = NA_integer_ ) class(defaults) <- "curvep_config" return(defaults) } run_rcurvep <- function(d, mask = 0, config = curvep_defaults(), keep_sets = c("act_set", "resp_set", "fp_set"), ...) { d <- na.omit(d) d <- .check_dat_base(d) mask <- .check_mask_input(mask, d) config <- .check_config_name(config = config, ...) config <- .check_config_value(config) keep_sets <- .check_keep_sets(keep_sets, c("act_set", "resp_set", "fp_set"), must_set = "act_set") d <- create_resp_mask(d, mask) out <- cal_curvep_dataset(d, config = config) result <- clean_curvep_output(out, config = config) merge_result <- merge_rcurvep_output(d = result, keep_sets = keep_sets) out_result <- list(result = merge_result, config = config) class(out_result) <- c("rcurvep", class(out_result)) return(out_result) } create_resp_mask <- function(d, mask) { if (any(is.null(mask))) { result <- d } else if (any(mask == 0)) { result <- d %>% dplyr::mutate(mask = 0) } else { result <- d %>% dplyr::arrange(.data$endpoint, .data$chemical, dplyr::desc(.data$conc)) %>% tidyr::nest(data = -c(.data$endpoint, .data$chemical)) %>% dplyr::mutate( mask = purrr::map(data, function(x, mask) replace(rep(0, nrow(x)), mask, 1), mask = mask) ) %>% tidyr::unnest(cols = c("data", "mask")) } return(result) } cal_curvep_dataset <- function(d, config) { d <- d %>% dplyr::arrange(.data$endpoint, .data$chemical, .data$conc) %>% tidyr::nest(input = -c(.data$endpoint, .data$chemical)) result <- d %>% dplyr::mutate( output = purrr::map( .data$input, function(x, config) call_curvep(x$conc, x$resp, x$mask, config), config = config) ) return(result) } clean_curvep_output <- function(d, config) { result <- d %>% dplyr::mutate( out_resp = purrr::map(.data$output, extract_curvep_outresp), in_summary = purrr::map(.data$input, extract_input_summary), fingerprint = purrr::map(.data$output, extract_curvep_fingerprint, config = config), activity = purrr::map(.data$output, extract_curvep_activity, config = config) ) %>% dplyr::select(-.data$output) return(result) } call_curvep <- function(concs, resps, masks, paras) { result <- do.call(curvep, c(list(concs), list(resps), list(masks), paras)) result[['Settings']] <- NULL return(result) } extract_curvep_fingerprint <- function(x, config) { outp <- x vals <- outp[names(outp) %in% c('xx', 'ECxx', 'Cxx')] result <- vals %>% tibble::as_tibble() result[result == config$DUMV] <- NA return(result) } extract_curvep_outresp <- function(x) { outp <- x vals <- outp[names(outp) %in% c('resp', 'corr')] result <- vals %>% tibble::as_tibble() result <- result %>% dplyr::rename( corrected_resp = .data$resp, correction = .data$corr ) return(result) } extract_input_summary <- function(x) { result <- tibble::tibble( lowest_conc = head(x$conc, 1), highest_conc = tail(x$conc, 1), max_resp = max(x$resp), min_resp = min(x$resp), n_conc = length(unique(x$conc)), mean_conc_spacing = mean(diff(unique(x$conc))) ) return(result) } extract_curvep_activity <- function(x, config) { outp <- x vals <- outp[!names(outp) %in% c('resp', 'corr', 'xx', 'ECxx', 'Cxx','Settings')] result <- vals %>% tibble::as_tibble() result[result == config$DUMV] <- NA return(result) }
find_peaks <- function(data, n_peaks=3){ .SD = peak = NULL out <- data.table::copy(data) out[ , peak := find_peaks_wapped(.SD, n_peaks = n_peaks), by = c(data.table::key(out))] out[, peak := ifelse(is.na(peak), 0L, peak)] } find_peaks_wapped <- function(d, n_peaks = 3){ signif_threshold = NULL x <- d[, power - signif_threshold] peak_mat <- pracma::findpeaks(x, peakpat = "[+]{1,}[0]*[-]{1,}", sortstr = TRUE, minpeakheight = 0 ) peak_idx <- rep(NA_real_,n_peaks) out <- rep(NA_integer_, nrow(d)) if(!is.null(peak_mat)) out[peak_mat[,2]] <- 1:nrow(peak_mat) out } findpeaks_pval <- function (x, nups = 1, ndowns = nups, zero = "0", peakpat = "[+]{1,}[0]*[-]{1,}", minpeakdistance = 1, threshold = 0, npeaks = 0, sortstr = FALSE){ stopifnot(is.vector(x, mode = "numeric") || length(is.na(x)) == 0) if (!zero %in% c("0", "+", "-")) stop("Argument 'zero' can only be '0', '+', or '-'.") xc <- paste(as.character(sign(diff(x))), collapse = "") xc <- gsub("1", "+", gsub("-1", "-", xc)) if (zero != "0") xc <- gsub("0", zero, xc) if (is.null(peakpat)) { peakpat <- sprintf("[+]{%d,}[-]{%d,}", nups, ndowns) } rc <- gregexpr(peakpat, xc)[[1]] if (rc[1] < 0) return(NULL) x1 <- rc x2 <- rc + attr(rc, "match.length") attributes(x1) <- NULL attributes(x2) <- NULL n <- length(x1) xv <- xp <- numeric(n) for (i in 1:n) { xp[i] <- which.max(x[x1[i]:x2[i]]) + x1[i] - 1 xv[i] <- x[xp[i]] } inds <- which( xv - pmax(x[x1], x[x2]) >= threshold) X <- cbind(xv[inds], xp[inds], x1[inds], x2[inds]) if (minpeakdistance < 1) warning("Handling 'minpeakdistance < 1' is logically not possible.") if (sortstr || minpeakdistance > 1) { sl <- sort.list(X[, 1], na.last = NA, decreasing = TRUE) X <- X[sl, , drop = FALSE] } if (length(X) == 0) return(c()) if (minpeakdistance > 1) { no_peaks <- nrow(X) badpeaks <- rep(FALSE, no_peaks) for (i in 1:no_peaks) { ipos <- X[i, 2] if (!badpeaks[i]) { dpos <- abs(ipos - X[, 2]) badpeaks <- badpeaks | (dpos > 0 & dpos < minpeakdistance) } } X <- X[!badpeaks, ] } if (npeaks > 0 && npeaks < nrow(X)) { X <- X[1:npeaks, , drop = FALSE] } return(X) }
NULL bq_dataset <- function(project, dataset) { assert_that(is.string(project), is.string(dataset)) structure( list( project = project, dataset = dataset ), class = "bq_dataset" ) } setOldClass("bq_dataset") print.bq_dataset <- function(x, ...) { cat_line("<bq_dataset> ", x$project, ".", x$dataset) invisible(x) } as_bq_dataset <- function(x) UseMethod("as_bq_dataset") as_bq_dataset.bq_dataset <- function(x) x as_bq_dataset.character <- function(x) { x <- bq_from_string(x, 2, "bq_dataset") bq_dataset(x[[1]], x[[2]]) } as_bq_dataset.list <- function(x) { x <- bq_from_list(x, c("projectId", "datasetId"), "bq_dataset") bq_dataset(x$projectId, x$datasetId) } bq_table <- function(project, dataset, table = NULL) { if (inherits(project, "bq_dataset") && is.null(table)) { return(bq_table(project$project, project$dataset, dataset)) } assert_that(is.string(project), is.string(dataset), is.string(table)) structure( list( project = project, dataset = dataset, table = table ), class = "bq_table" ) } setOldClass("bq_table") print.bq_table <- function(x, ...) { cat_line("<bq_table> ", x$project, ".", x$dataset, ".", x$table) invisible(x) } as_bq_table <- function(x, ...) UseMethod("as_bq_table") as_bq_table.bq_table <- function(x, ...) { x } as_bq_table.character <- function(x, ...) { x <- bq_from_string(x, 3, "bq_table") bq_table(x[[1]], x[[2]], x[[3]]) } as_bq_table.list <- function(x, ...) { x <- bq_from_list(x, c("projectId", "datasetId", "tableId"), "bq_table") bq_table(x$projectId, x$datasetId, x$tableId) } bq_job <- function(project, job, location = "US") { structure( list( project = project, job = job, location = location ), class = "bq_job" ) } as_bq_job <- function(x) UseMethod("as_bq_job") as_bq_job.bq_job <- function(x) x as_bq_job.list <- function(x) { x <- bq_from_list(x, c("projectId", "jobId", "location"), "bq_job") bq_job(x$projectId, x$jobId, x$location) } as_bq_job.character <- function(x) { x <- bq_from_string(x, 3, "bq_job") bq_job(x[[1]], x[[2]], x[[3]]) } print.bq_job <- function(x, ...) { cat_line("<bq_job> ", as.character(x)) invisible(x) } as.character.bq_job <- function(x, ...) { paste0(x$project, ".", x$job, ".", x$location) } datasetReference <- function(x) { x <- as_bq_dataset(x) list( projectId = unbox(x$project), datasetId = unbox(x$dataset) ) } tableReference <- function(x) { x <- as_bq_table(x) list( projectId = unbox(x$project), datasetId = unbox(x$dataset), tableId = unbox(x$table) ) } bq_from_list <- function(x, names, type) { names(x) <- camelCase(names(x)) if (length(setdiff(names, names(x))) == 0) return(x) names_str <- glue_collapse(names, sep = ", ", last = " and ") stop(glue("List <{type}> must have components {names_str}"), call. = FALSE) } bq_from_string <- function(x, n, type) { assert_that(is.string(x)) pieces <- strsplit(x, ".", fixed = TRUE)[[1]] if (length(pieces) != n) { stop( glue("Character <{type}> must contain {n} components when split by `.`"), call. = FALSE ) } pieces }
library(dreamerr) test_err = function(x){ a = try(x, silent = TRUE) if(!any(class(a) == "try-error")) stop("Expected an error that did not occur.") invisible(NULL) } test_scalar = function(x1, x2, x3, x4, x5){ check_arg(x1, "numeric scalar") check_arg(x2, "integer scalar na ok") check_arg(x3, "scalar(factor, logical)") check_arg(x4, "scalar(integer, character, logical)") check_arg(x5, "integer scalar GT{-3} LE{3}") invisible(NULL) } test_scalar(x1 = 1) test_scalar(x1 = -1) test_scalar(x1 = exp(55)) test_scalar(x2 = 1) test_scalar(x2 = NA) test_scalar(x3 = factor("a", "a")) test_scalar(x3 = TRUE) test_scalar(x4 = 5) test_scalar(x4 = "bon") test_scalar(x4 = TRUE) test_scalar(x5 = -2) test_scalar(x5 = 3) test_err(test_scalar("5")) test_err(test_scalar(NA)) test_err(test_scalar(iris)) test_err(test_scalar(x2 = 1.1)) test_err(test_scalar(x2 = c(NA, 1))) test_err(test_scalar(x3 = "5")) test_err(test_scalar(x3 = 1)) test_err(test_scalar(x4 = 5.5)) test_err(test_scalar(x5 = -3)) test_err(test_scalar(x5 = 3.1)) test_vec = function(x1, x2, x3, x4, x5, x6){ check_arg(x1, "integer vector") check_arg(x2, "numeric vector no na GE{0}") check_arg(x3, "vector(logical, character)") check_arg(x4, "vector len(2,5)") check_arg(x5, "numeric vector len(data)", .data = iris) check_arg(x6, "integer vector len(value) no na GT{5}", .value = 3) invisible(NULL) } test_vec(x1 = 5) test_vec(x1 = 5:6) test_vec(x1 = TRUE) test_vec(x2 = 1.1) test_vec(x2 = iris$Sepal.Length) test_vec(x2 = c(55, 32)) test_vec(x3 = c(TRUE, NA, FALSE)) test_vec(x3 = TRUE) test_vec(x3 = c("bon", NA, "jour")) test_vec(x4 = c(TRUE, NA)) test_vec(x4 = c("bon", NA, "jour", NA, NA)) test_vec(x5 = iris$Sepal.Width) test_vec(x6 = c(6, 7, 8)) test_err(test_vec(x1 = 5.5)) test_err(test_vec(x1 = 0.5 + 1:2)) test_err(test_vec(x2 = -1.1)) test_err(test_vec(x2 = c(NA, 55))) test_err(test_vec(x3 = 55)) test_err(test_vec(x4 = TRUE)) test_err(test_vec(x5 = iris$Species)) test_err(test_vec(x5 = 1:5)) test_err(test_vec(x6 = c(6, NA, 8))) test_err(test_vec(x6 = c(5, 7, 8))) test_err(test_vec(x6 = c(7, 8))) test_list = function(x1, x2, x3){ check_arg(x1, "list l0") check_arg(x2, "list len(2)") check_arg(x3, "list len(value)", .value = 2) invisible(NULL) } test_list(x1 = iris) test_list(x1 = list()) test_list(x2 = iris[1:2]) test_list(x2 = list(a = 5, b = 6)) test_list(x3 = list(a = 5, b = 6)) test_err(test_list(x1 = 1:5)) test_err(test_list(x2 = iris[1])) test_err(test_list(x3 = list(a = 5, b = 6, c = 9))) test_df = function(x1, x2){ check_arg(x1, "data.frame nrow(10,) ncol(,2)") check_arg(x2, "vdata.frame no na") invisible(NULL) } test_df(x1 = iris[, 1:2]) test_df(x1 = data.frame(a = 1:10)) test_df(x2 = iris[, 1:2]) test_df(x2 = 1:5) test_df(x2 = iris$Sepal.Length) test_err(test_df(x1 = iris[1:5, 1:2])) test_err(test_df(x1 = iris)) test_err(test_df(x2 = data.frame(a = c(NA, 1:5)))) test_err(test_df(x2 = c(NA, 1:5))) test_mat = function(x1, x2, x3, x4, x5){ check_arg(x1, "square numeric matrix GT{0}") check_arg(x2, "vmatrix no na nrow(10, )") invisible(NULL) } test_mat(x1 = matrix(5, 5, 5)) test_mat(x1 = matrix(c(NA, 5), 6, 6)) test_mat(x2 = 1:10) test_mat(x2 = matrix(rnorm(20*25), 20, 25)) test_err(test_mat(x1 = matrix(-5, 5, 5))) test_err(test_mat(x1 = matrix(5, 6, 5))) test_err(test_mat(x1 = matrix("bonjour", 6, 5))) test_err(test_mat(x1 = 1)) test_err(test_mat(x2 = 1:5)) test_err(test_mat(x2 = c(NA, 1:10))) test_err(test_mat(x2 = matrix(55, 5, 20))) test_fml = function(x1, x2, x3, x4, x5){ check_arg(x1, "ts formula") check_arg(x2, "os formula right(2)") check_arg(x3, "formula left(, 1)") check_arg(x4, "formula var(data)", .data = iris) check_arg(x5, "formula var(env)") invisible(NULL) } test_fml(x1 = a ~ b + c) test_fml(x1 = a | b ~ b + c | d + e) test_fml(x2 = ~ b + c | d) test_fml(x3 = a ~ b + c) test_fml(x3 = a ~ 1 | 0 | z) test_fml(x4 = Petal.Length ~ Sepal.Length | Species) x = y = 5 test_fml(x5 = y ~ x) test_err(test_fml(x1 = iris)) test_err(test_fml(x1 = 1:5)) test_err(test_fml(x1 = ~ b + c)) test_err(test_fml(x2 = ~ b + c | d | e)) test_err(test_fml(x2 = a ~ b + c | d)) test_err(test_fml(x3 = a | b ~ b + c)) test_err(test_fml(x4 = Petol.Length ~ Sepal.Length | Species)) test_err(test_fml(x4 = Petol.Length ~ Sepal.Length | species)) x = y = 5 test_err(test_fml(x5 = y ~ xxx)) test_charin = function(x1, x2){ check_arg(x1, "charin", .choices = c("bon", "jour", "so", "leil")) check_arg(x2, "multi charin(bon, jour, so, leil)") invisible(NULL) } test_charin(x1 = "bon") test_charin(x1 = "jour") test_charin(x2 = c("bon", "jour")) test_err(test_charin(x1 = "bonj")) test_err(test_charin(x1 = "Bon")) test_err(test_charin(x1 = c("bon", "jour"))) test_err(test_charin(x2 = 55)) test_match = function(x1 = c("bon", "jour", "soleil"), x2, x3){ check_arg_plus(x1, "match") check_arg_plus(x2, "strict match(bon, jour, soleil)") check_arg_plus(x3, "multi match", .choices = c("bon", "jour", "soleil")) invisible(NULL) } test_match(x1 = "jour") test_match(x1 = "s") test_match(x1 = "So") test_match(x1 = "Bo") test_match(x2 = "jour") test_match(x2 = "s") test_match(x3 = c("jour", "bo")) test_err(test_match(x1 = "jouro")) test_err(test_match(x1 = 55)) test_err(test_match(x1 = ".+")) test_err(test_match(x2 = "Jour")) test_err(test_match(x2 = c("jour", "b"))) test_err(test_match(x3 = NA)) test_na = function(x1){ check_arg(x1, "NA") invisible(NULL) } test_na(x1 = NA) test_err(test_na(x1 = 5)) test_err(test_na(x1 = 5:55)) test_err(test_na(x1 = iris)) test_err(test_na(x1 = c(NA, 2))) test_err(test_na(x1 = lis(NA))) test_fun = function(x1, x2, x3, x4, x5){ check_arg(x1, "function") check_arg(x2, "function arg(1,)") invisible(NULL) } test_fun(x1 = sum) test_fun(x2 = merge) test_err(test_fun(x1 = 1:5)) test_err(test_fun(x2 = function() 5))
`HierarchicalSparseCluster` <- function(x=NULL, dists=NULL, method=c("average", "complete", "single","centroid"), wbound=NULL,niter=15,dissimilarity=c("squared.distance", "absolute.value"), uorth=NULL, silent=FALSE, cluster.features=FALSE, method.features=c("average", "complete", "single","centroid"),output.cluster.files=FALSE, outputfile.prefix="output",genenames=NULL, genedesc=NULL,standardize.arrays=FALSE){ method <- match.arg(method) method.features <- match.arg(method.features) dissimilarity <- match.arg(dissimilarity) if (is.null(x) && is.null(dists)) stop("x or dists must be given!!!") xorig <- x if(standardize.arrays){ if(is.null(x)) stop("Cannot standardize arrays if x not given.") dists <- NULL x <- sweep(x,1,apply(x,1,mean,na.rm=TRUE),"-") x <- sweep(x,1,apply(x,1,sd,na.rm=TRUE),"/") } if(is.null(dists)){ xnona <- x xnona[is.na(x)] <- 0 dists <- matrix(distfun(xnona), ncol=ncol(x)) if(sum(is.na(x))>0){ xbinary <- matrix(1, nrow=nrow(x),ncol=ncol(x)) xbinary[is.na(x)] <- 0 mult <- matrix(multfun(xbinary),ncol=ncol(x)) if(dissimilarity=="squared.distance"){ dists <- sweep(dists,1,sqrt(ncol(dists)/apply(mult!=0,1,sum)),"*") } else if (dissimilarity=="absolute.value"){ dists <- sweep(dists,1,ncol(dists)/apply(mult!=0,1,sum),"*") } dists[mult==0] <- 0 mult <- NULL xbinary <- NULL xnona <- NULL } } if(is.null(wbound)) wbound <- .5*sqrt(ncol(dists)) if(wbound<=1) stop("Cannot have wbound <= 1") if (dissimilarity == "squared.distance") out <- GetUW(dists^2, wbound, niter = niter, uorth = uorth, silent = silent) if (dissimilarity == "absolute.value") out <- GetUW(dists, wbound, niter = niter, uorth = uorth, silent = silent) out <- list(hc = hclust(as.dist(out$u), method = method), ws = out$w, u = out$u, crit = out$crit, dists = dists, uorth = uorth, wbound = wbound) if(cluster.features){ if(is.null(x)) stop("Cannot cluster features unless x is given.") rho=cor(xorig[,out$ws!=0],use="pairwise.complete.obs") out2 <- hclust(as.dist(2*(1-rho)), method=method.features) out$hc.features <- out2 } if(output.cluster.files){ if(is.null(x)) stop("Cannot output files unless x is given.") output.cluster.files.fun(xorig,out,outputfile.prefix,genenames=genenames,genedesc=genedesc) } if(!silent) cat(fill=TRUE) class(out) <- "HierarchicalSparseCluster" return(out) } plot.HierarchicalSparseCluster <- function(x,...){ par(mfrow=c(1,2)) plot(x$hc,xlab="",ylab="",sub="", main="Sparse Clustering", labels=rep("", nrow(x$u))) plot(x$ws, main=paste("Wbound is ", sep="", round(x$wbound,3)), xlab="Feature Index", ylab="Wj") } print.HierarchicalSparseCluster <- function(x,...){ cat("Wbound is ", x$wbound, ":", fill=TRUE) cat("Number of non-zero weights: ", sum(x$ws!=0), fill=TRUE) cat("Sum of weights: ", sum(x$ws), fill=TRUE) cat(fill=TRUE) }
glm.scoretest <- function(fit, x2, dispersion=NULL) { w <- fit$weights r <- fit$residuals if(any(w <= 0)) { r <- r[w>0] x2 <- x2[w>0] w <- w[w>0] } if (is.null(dispersion)) { fixed.dispersion <- (fit$family$family %in% c("poisson","binomial")) if(fixed.dispersion) dispersion <- 1 else if(fit$df.residual > 0) { dispersion <- sum(w*r^2)/fit$df.residual } else { stop("No residual df available to estimate dispersion") } } ws <- sqrt(w) x2.1w <- qr.resid(fit$qr,ws*x2) zw <- ws*r colSums(as.matrix(x2.1w*zw))/sqrt(colSums(as.matrix(x2.1w * x2.1w)))/sqrt(dispersion) }
NULL append_rhs.formula <- function(object = NULL, newterms, keep.onesided = FALSE, env = environment(object)){ if(is.null(object)) keep.onesided <- TRUE if(inherits(newterms,"formula")) newterms <- list_rhs.formula(newterms) for(i in seq_along(newterms)){ newterm <- newterms[[i]] termsign <- if(NVL(attr(newterms, "sign")[i], +1)>0) "+" else "-" if(length(object)==0){ if(termsign == "-") newterm <- call(termsign, newterm) object <- as.formula(call("~", newterm), env = env) }else if(length(object)==3) object[[3L]]<-call(termsign,object[[3L]],newterm) else if(keep.onesided) object[[2L]]<-call(termsign,object[[2L]],newterm) else object[[3L]]<- if(termsign=="+") newterm else call(termsign,newterm) } object } append.rhs.formula<-function(object,newterms,keep.onesided=FALSE){ .Deprecate_once("append_rhs.formula") append_rhs.formula(object,newterms,keep.onesided) } filter_rhs.formula <- function(object, f, ...){ rhs <- ult(object) SnD <- function(x){ if(!f(x, ...)) return(NULL) if(is(x, "call")){ op <- x[[1L]] if(! as.character(op)%in%c("+","-")) return(x) else if(length(x)==2){ arg <- SnD(x[[2L]]) if(is.null(arg)) return(NULL) else return(call(as.character(op), arg)) }else if(length(x)==3){ arg1 <- SnD(x[[2L]]) arg2 <- SnD(x[[3L]]) if(is.null(arg2)) return(arg1) else if(is.null(arg1)){ if(as.character(op)=="+") return(arg2) else return(call(as.character(op), arg2)) } else return(call(as.character(op), arg1, arg2)) }else stop("Unsupported type of formula passed.") }else return(x) } rhs <- SnD(rhs) ult(object) <- rhs object } nonsimp_update.formula<-function (object, new, ..., from.new=FALSE){ old.lhs <- if(length(object)==2) NULL else object[[2L]] old.rhs <- if(length(object)==2) object[[2L]] else object[[3L]] new.lhs <- if(length(new)==2) NULL else new[[2L]] new.rhs <- if(length(new)==2) new[[2L]] else new[[3L]] sub.dot <- function(c, dot){ if(is.name(c) && c==".") dot else if(is.call(c)) as.call(c(list(c[[1L]]), lapply(c[-1], sub.dot, dot))) else c } deparen<- function(c, ops = c("+","*")){ if(is.call(c)){ if(as.character(c[[1L]]) %in% ops){ op <- as.character(c[[1L]]) if(length(c)==2 && is.call(c[[2L]]) && c[[2L]][[1L]]==op) return(deparen(c[[2L]], ops)) else if(length(c)==3 && is.call(c[[3L]]) && c[[3L]][[1L]]==op){ if(length(c[[3L]])==3) return(call(op, call(op, deparen(c[[2L]],ops), deparen(c[[3L]][[2L]],ops)), deparen(c[[3L]][[3L]],ops))) else return(call(op, deparen(c[[2L]],ops), deparen(c[[3L]][[2L]],ops))) } } return(as.call(c(list(c[[1L]]), lapply(c[-1], deparen, ops)))) }else return(c) } out <- if(length(new)==2) call("~", deparen(sub.dot(new.rhs, old.rhs))) else if(length(object)==2) call("~", deparen(sub.dot(new.lhs, quote(expr=))), deparen(sub.dot(new.rhs, old.rhs))) else call("~", deparen(sub.dot(new.lhs, old.lhs)), deparen(sub.dot(new.rhs, old.rhs))) if(identical(out[[2]], quote(expr=))) out <- out[-2] if(identical(from.new,FALSE)){ e <- environment(object) }else{ e <- new.env(parent=environment(object)) if(identical(from.new,TRUE)) from.new <- setdiff(ls(pos=environment(new), all.names=TRUE), "...") for(name in from.new) assign(name, get(name, pos=environment(new)), pos=e) } as.formula(out, env = e) } nonsimp.update.formula<-function (object, new, ..., from.new=FALSE){ .Deprecate_once("nonsimp_update.formula") nonsimp_update.formula(object, new, ..., from.new=from.new) } .recurse_summation <- function(x, sign){ if(length(x)==1) {out <- list(x); attr(out,"sign")<-sign; out} else if(length(x)==2 && x[[1L]]=="+") .recurse_summation(x[[2L]],sign) else if(length(x)==2 && x[[1L]]=="-") .recurse_summation(x[[2L]],-sign) else if(length(x)==3 && x[[1L]]=="+") { l1 <- .recurse_summation(x[[2L]],sign) l2 <- .recurse_summation(x[[3L]],sign) out <- c(l1, l2) attr(out,"sign") <- c(attr(l1,"sign"), attr(l2,"sign")) out } else if(length(x)==3 && x[[1L]]=="-"){ l1 <- .recurse_summation(x[[2L]],sign) l2 <- .recurse_summation(x[[3L]],-sign) out <- c(l1, l2) attr(out,"sign") <- c(attr(l1,"sign"), attr(l2,"sign")) out } else if(x[[1L]]=="(") .recurse_summation(x[[2L]], sign) else {out <- list(x); attr(out,"sign")<-sign; out} } term.list.formula<-function(rhs, sign=+1){ .Deprecate_once("list_rhs.formula") .recurse_summation(rhs, sign) } list_summands.call<-function(object){ .recurse_summation(object, sign=+1) } list_rhs.formula<-function(object){ if (!is(object, "formula")) stop("Invalid formula of class ",sQuote(class(object)),".") .recurse_summation(ult(object), sign=+1) } eval_lhs.formula <- function(object){ if (!is(object, "formula")) stop("Invalid formula of class ",sQuote(class(object)),".") if(length(object)<3) stop("Formula given is one-sided.") eval(object[[2L]],envir=environment(object)) } trim_env <- function(object, keep=NULL, ...){ UseMethod("trim_env") } trim_env.environment <- function(object, keep=NULL, ...){ e <- new.env(parent=baseenv()) for(vn in keep){ try(assign(vn, get(vn, envir=object), envir=e), silent=TRUE) } e } trim_env.default <- function(object, keep=NULL, ...){ environment(object) <- trim_env(environment(object), keep, ...) object } empty_env <- function(object){ environment(object) <- emptyenv() object } base_env <- function(object){ environment(object) <- baseenv() object }
gboot_block<-function(data,var,model,B=1000,L1=2,L2=2){ lat=long=block=value=Distance=Semivariance=NULL if(is.geodata(data) == T){ }else{ stop("Object data is not of the class geodata") } if(isTRUE(class(var) == "variogram")){ }else{ stop("Object var is not of the class variogram") } if(isTRUE(class(model)[1] == "variomodel") & isTRUE(class(model)[2] == "variofit")){ }else{ stop("Object model is not of the class variomodel/variofit") } if(B >0 ){ }else{ stop("Object B must be positive") } quiet<-function(x){ invisible(capture.output(x))} model_name<-substr(model$cov.model,1,3) max_dist<-var$max.dist bin<-length(var$u) var_df<-matrix(0, nrow=B, ncol=bin) pars<-data.frame(C0=rep(0,B), C1=rep(0,B), a=rep(0,B), Sill=rep(0,B), `Pratical Range`=rep(0,B)) x<-var$u c0<-model$nugget c1<-model$cov.pars[1] a<-model$cov.pars[2] pars_or<-data.frame(C0=c0, Sill=c0+c1, C1=c1, a=a, PR=model$practicalRange) df_new <- data.frame(lat=data[[1]][,1], long=data[[1]][,2], value=data[[2]]) df_new <- within(df_new, { x = cut(lat , L1, labels = FALSE) y = cut(long, L2, labels = FALSE) }) df_new$block<-paste0(df_new$y,df_new$x) df_new %>% group_by(x) %>% mutate(lat=max(lat)) %>% group_by(y) %>% mutate(long=max(long)) ->teste p1<-df_new %>% ggplot(aes(lat,long,col=block))+ geom_point()+ labs(x="Latitude",y="Longitude",col="Block:")+ coord_equal()+ theme_minimal()+ geom_vline(data=teste,aes(xintercept=lat),linetype="dashed")+ geom_hline(data=teste,aes(yintercept=long),linetype="dashed")+ ylim(min(df_new$long),max(df_new$long))+ xlim(min(df_new$lat),max(df_new$lat)) sample<-data for(i in 1:B ){ sample$data<- df_new %>% group_by(block) %>% nest() %>% sample_frac() %>% unnest() %>% select(value) quiet(var_new<-variog(sample, max.dist=max_dist)) var_df[i,]<-var_new$v quiet(mod_new<-variofit(var_new, ini.cov.pars=c(c1,a), nugget=c0, cov.model=model_name)) pars[i,]<-c(as.numeric(summary(mod_new)$estimated.pars[1]), sum(as.numeric(c(summary(mod_new)$estimated.pars)[1:2])), as.numeric(c(summary(mod_new)$estimated.pars[2:3])), mod_new$practicalRange) } var_df<-as.data.frame(var_df) names(var_df)<-paste("Class",letters[1:bin]) var_df<-gather(var_df,Distance,Semivariance) var_df$B<-rep(1:B,bin) var_aux<-data.frame(Distance=paste("Class",letters[1:bin]),Semivariance=var$v) var_aux$Length<-var$u names(pars)<-c("Nugget","Sill","Contribution","Range","Practical Range") names(pars_or)<-c("Nugget","Sill","Contribution","Range","Practical Range") print(p1) return(list(variogram_boot=var_df, variogram_or=var_aux, pars_boot=pars, pars_or=pars_or)) }
library(generator) context("r_ipv4_addresses()") test_that("Produces the correct output.", { expect_equal(length(r_ipv4_addresses(100)), 100) }) test_that("Produces the correct output type.", { expect_is(r_ipv4_addresses(100), "character") }) test_that("Produces the correct errors.", { })
calculateAT6 <- function(data, ref, amount = NULL, weighted = TRUE, alpha = 0.05, ignore.case = TRUE, debug = FALSE) { if (debug) { print(paste("IN:", match.call()[[1]])) print("Parameters:") print("data") print(str(data)) print("ref") print(str(ref)) print("amount") print(str(amount)) print("weighted") print(weighted) print("alpha") print(alpha) print("ignore.case") print(ignore.case) } if (!"Sample.Name" %in% names(data)) { stop("'data' must contain a column 'Sample.Name'") } if (!"Marker" %in% names(data)) { stop("'data' must contain a column 'Marker'") } if (!"Allele" %in% names(data)) { stop("'data' must contain a column 'Allele'") } if (!"Height" %in% names(data)) { stop("'data' must contain a column 'Height'") } if (is.null(amount)) { if (!"Amount" %in% names(data)) { stop("'data' must contain a column 'Amount'") } } else { if (!"Sample.Name" %in% names(amount)) { stop("'amount' must contain a column 'Sample.Name'") } if (!"Amount" %in% names(amount)) { stop("'amount' must contain a column 'Amount'") } } if (sum(grepl("Allele", names(data))) > 1) { stop("'data' must be in 'slim' format", call. = TRUE ) } if (sum(grepl("Height", names(data))) > 1) { stop("'data' must be in 'slim' format", call. = TRUE ) } if (!"Sample.Name" %in% names(ref)) { stop("'ref' must contain a column 'Sample.Name'") } if (!"Marker" %in% names(ref)) { stop("'ref' must contain a column 'Marker'") } if (!"Allele" %in% names(ref)) { stop("'ref' must contain a column 'Allele'") } if (sum(grepl("Allele", names(ref))) > 1) { stop("'ref' must be in 'slim' format", call. = TRUE ) } if (!is.logical(weighted)) { stop("'weighted' must be logical", call. = TRUE ) } if (!is.numeric(alpha) | alpha < 0 | alpha > 1) { stop("'alpha' must be numeric [0,1]", call. = TRUE ) } if (!is.logical(ignore.case)) { stop("'ignore.case' must be logical", call. = TRUE ) } dfHeight <- calculateHeight( data = data, ref = ref, na.replace = 0, add = FALSE, exclude = NULL, sex.rm = FALSE, qs.rm = FALSE, kit = NULL, ignore.case = ignore.case, exact = FALSE, debug = debug ) if (is.null(amount)) { dfHeight <- addData( data = dfHeight, new.data = data, by.col = "Sample.Name", then.by.col = NULL, exact = TRUE, ignore.case = ignore.case, what = "Amount", debug = debug ) message("Amount added to 'data'.") } else { dfHeight <- addData( data = dfHeight, new.data = amount, by.col = "Sample.Name", then.by.col = NULL, exact = TRUE, ignore.case = ignore.case, what = "Amount", debug = debug ) message("Amount added to 'data'.") } message("Processed data to be used in regression:") print(dfHeight) if (!is.numeric(dfHeight$H)) { dfHeight$H <- as.numeric(dfHeight$H) message("'H' must be numeric. 'data' converted!") } if (!is.numeric(dfHeight$Amount)) { dfHeight$Amount <- as.numeric(dfHeight$Amount) message("'Amount' must be numeric. 'data' converted!") } if (any(is.na(dfHeight$Amount))) { dfHeight <- dfHeight[!is.na(dfHeight$Amount), ] message("Removed rows where Amount=NA.") } dt <- data.table::data.table(dfHeight) dfSd <- dt[, list(H = mean(H), Sd = sd(H)), by = Amount] n <- nrow(dfSd) if (weighted) { weight <- 1 / dfSd$Sd^2 fit <- lm(dfSd$H ~ dfSd$Amount, weights = weight) coeff <- c(summary(fit)$coef[1:2], summary(fit)$sigma) if (debug) { print("coeff:") print(coeff) print("Intercept:") print(coeff[1]) print("Slope:") print(coeff[2]) print("Std.Error:") print(coeff[3]) } res <- data.frame( Amount = dfSd$Amount, Height = dfSd$H, Sd = dfSd$Sd, Weight = weight, N = n, Alpha = alpha, Lower = as.numeric(coeff[1] - qt(alpha, n - 1, lower.tail = FALSE) * coeff[3]), Intercept = as.numeric(coeff[1]), AT6 = as.numeric(coeff[1] + qt(alpha, n - 1, lower.tail = FALSE) * coeff[3]), Std.Error = coeff[3], Slope = coeff[2] ) } else { fit <- lm(dfSd$H ~ dfSd$Amount) coeff <- c(summary(fit)$coef[1:2], summary(fit)$sigma) if (debug) { print("coeff:") print(coeff) print("Intercept:") print(coeff[1]) print("Slope:") print(coeff[2]) print("Std.Error:") print(coeff[3]) } res <- data.frame( Amount = dfSd$Amount, Height = dfSd$H, Sd = dfSd$Sd, Weight = NA, N = n, Alpha = alpha, Lower = as.numeric(coeff[1] - qt(alpha, n - 1, lower.tail = FALSE) * coeff[3]), Intercept = as.numeric(coeff[1]), AT6 = as.numeric(coeff[1] + qt(alpha, n - 1, lower.tail = FALSE) * coeff[3]), Std.Error = coeff[3], Slope = coeff[2] ) } if (debug) { print("str(res)") print(str(res)) print("head(res)") print(head(res)) print("tail(res)") print(tail(res)) } res <- auditTrail(obj = res, f.call = match.call(), package = "strvalidator") if (debug) { print(paste("EXIT:", match.call()[[1]])) } return(res) }
mtabulate <- function(vects) { lev <- sort(unique(unlist(vects))) dat <- do.call(rbind, lapply(vects, function(x, lev){ tabulate(factor(x, levels = lev, ordered = TRUE), nbins = length(lev))}, lev = lev)) colnames(dat) <- sort(lev) data.frame(dat, check.names = FALSE) }
setClass("studentDist", slots = c(df = "numeric", mu = "numeric", sd = "numeric")) setValidity("studentDist", function(object) { if (object@sd <= 0) return("sd parameter must be positive.") if (object@df <= 0) return("df parameter must be positive.") return(TRUE) } )
local_conditional_expectations <- function(explainer, observations, y = NULL, variable_splits = NULL, variables = NULL, grid_points = 101) { if (!("explainer" %in% class(explainer))) stop("The local_conditional_expectations() function requires an object created with explain() function.") predict_function <- explainer$predict_function model <- explainer$model if (is.null(variable_splits)) { if (is.null(explainer$data)) stop("The local_conditional_expectations() function requires explainers created with specified 'data'.") if (is.null(variables)) variables <- intersect(colnames(explainer$data), colnames(observations)) variable_splits <- calculate_variable_splits(explainer$data, variables = variables, grid_points = grid_points) } profiles <- calculate_profiles_lce(observations, variable_splits, model, dataset = explainer$data, predict_function) profiles$`_label_` <- explainer$label observations$`_yhat_` <- predict_function(model, observations) if (!is.null(y)) observations$`_y_` <- y observations$`_label_` <- explainer$label attr(profiles, "observations") <- observations class(profiles) = c("ceteris_paribus_explainer", "data.frame") profiles }
NULL class.name = "Cat" setClassUnion("logicalORnumeric", c("numeric","logical")) setClassUnion("numericORlist", c("numeric","list")) setClass("Cat", slots = list( ids = "character", guessing = "numeric", discrimination = "numeric", difficulty = "numericORlist", answers = "logicalORnumeric", priorName = "character", priorParams = "numeric", lowerBound = "numeric", upperBound = "numeric", model = "character", estimation = "character", estimationDefault = "character", selection = "character", z = "numeric", lengthThreshold = "logicalORnumeric", seThreshold = "logicalORnumeric", infoThreshold = "logicalORnumeric", gainThreshold = "logicalORnumeric", lengthOverride = "logicalORnumeric", gainOverride = "logicalORnumeric"), prototype = prototype( ids = paste0("Q", 1:10), guessing = rep(0, 10), discrimination = rep(0, 10), difficulty = rep(0, 10), answers = rep(NA, 10), priorName = "NORMAL", priorParams = c(0,1), lowerBound = -5, upperBound = 5, model = "ltm", estimation = "EAP", estimationDefault = "MAP", selection = "EPV", z = 0.9, lengthThreshold = NA, seThreshold = NA, infoThreshold = NA, gainThreshold = NA, lengthOverride = NA, gainOverride = NA)) setMethod("initialize", "Cat", function(.Object, ...) { .Object <- callNextMethod() validObject(.Object) return(.Object) }) setValidity("Cat", function(object){ if(length(unique(object@ids)) != length(object@answers)){ stop("Question id's must be unique.") } if(object@model == "ltm" | object@model == "tpm"){ if(any(!object@answers %in% c(0, 1, NA, -1))){ stop("Answer for binary model is not valid.") } } if(object@model == "grm" | object@model == "gpcm"){ for(i in 1:length(object@answers)){ max_option <- length(object@difficulty[[i]])+1 if(!object@answers[i] %in% c(NA, -1:max_option)){ stop("Answer for categorical model is not valid.") } } } if(! length(object@discrimination) > 1){ stop("Discrimination needs length greater than 1.") } if(! length(object@discrimination) == length(object@guessing)){ stop("Discrimination and guessing need to be same length.") } if(! length(object@discrimination) == length(object@answers)){ stop("Discrimination and answers need to be same length.") } if(! length(object@discrimination)==length(object@difficulty)){ stop("Discrimination and difficulty need to be same length.") } if(object@model == "grm" | object@model == "gpcm"){ if(class(object@difficulty) != "list") stop("Difficulty needs to be a list.") } if(object@upperBound < object@lowerBound){ stop("Lower bound value must be less than upper bound value.") } if(object@model == "grm"){ for(i in object@difficulty){ sorted <- sort(i) uniques <- unique(sorted) if(sum(sorted != i) > 0){ stop("Difficulty values must be increasing.") } if(length(uniques) != length(i)){ stop("Difficulty values must be unique within each item.") } } } if(sum(is.na(object@discrimination)) > 0){ stop("Discrimination values cannot be NA.") } if(object@priorName == 'UNIFORM'){ if(object@estimation != "EAP"){ stop("Uniform prior requires EAP estimation.") } } if(sum(is.na(object@guessing)) > 0){ stop("Guessing values cannot be NA.") } if(sum(object@guessing < 0) > 0 | sum(object@guessing > 1) > 0){ stop("Guessing values must be between 0 and 1.") } model_options = c("ltm", "grm", "gpcm", "tpm") if(! object@model %in% model_options){ stop("Model is not valid. Must be 'ltm', 'tpm', 'grm' or 'gpcm'.") } estimation_options = c("EAP", "MAP", "MLE", "WLE") if(! object@estimation %in% estimation_options){ stop("Estimation method is not valid. Must be 'EAP', 'MAP', 'MLE', or 'WLE'.") } estdefault_options = c("EAP", "MAP") if(! object@estimationDefault %in% estdefault_options){ stop("Estimation default method is not valid. Must be 'EAP' or 'MAP'.") } prior_options <- c("NORMAL", "STUDENT_T", "UNIFORM") if(! object@priorName %in% prior_options){ stop("Prior name is not valid.") } selection_options = c("EPV", "MEI", "MFI", "MPWI", "MLWI", "KL", "LKL", "PKL", "MFII", "RANDOM") if(!object@selection %in% selection_options){ stop("Selection method is not valid.") } }) NULL setGeneric("setGuessing<-", function(catObj, value) standardGeneric("setGuessing<-")) setReplaceMethod("setGuessing", "Cat", definition = function(catObj, value){ slot(catObj, "guessing") <- value validObject(catObj) return(catObj) }) setGeneric("setDiscrimination<-", function(catObj, value) standardGeneric("setDiscrimination<-")) setReplaceMethod("setDiscrimination", "Cat", definition = function(catObj, value){ slot(catObj, "discrimination") <- value validObject(catObj) return(catObj) }) setGeneric("setDifficulty<-", function(catObj, value) standardGeneric("setDifficulty<-")) setReplaceMethod("setDifficulty", "Cat", definition = function(catObj, value){ slot(catObj, "difficulty") <- value validObject(catObj) return(catObj) }) setGeneric("setAnswers<-", function(catObj, value) standardGeneric("setAnswers<-")) setReplaceMethod("setAnswers", "Cat", definition = function(catObj, value){ slot(catObj, "answers") <- value validObject(catObj) return(catObj) }) setGeneric("setIds<-", function(catObj, value) standardGeneric("setIds<-")) setReplaceMethod("setIds", "Cat", definition = function(catObj, value){ slot(catObj, "ids") <- value validObject(catObj) return(catObj) }) setGeneric("setModel<-", function(catObj, value) standardGeneric("setModel<-")) setReplaceMethod("setModel", "Cat", definition = function(catObj, value){ slot(catObj, "model") <- value validObject(catObj) return(catObj) }) setGeneric("setPriorName<-", function(catObj, value) standardGeneric("setPriorName<-")) setReplaceMethod("setPriorName", "Cat", definition = function(catObj, value){ slot(catObj, "priorName") <- value validObject(catObj) return(catObj) }) setGeneric("setPriorParams<-", function(catObj, value) standardGeneric("setPriorParams<-")) setReplaceMethod("setPriorParams", "Cat", definition = function(catObj, value){ slot(catObj, "priorParams") <- value validObject(catObj) return(catObj) }) setGeneric("setLowerBound<-", function(catObj, value) standardGeneric("setLowerBound<-")) setReplaceMethod("setLowerBound", "Cat", definition = function(catObj, value){ slot(catObj, "lowerBound") <- value validObject(catObj) return(catObj) }) setGeneric("setUpperBound<-", function(catObj, value) standardGeneric("setUpperBound<-")) setReplaceMethod("setUpperBound", "Cat", definition = function(catObj, value){ slot(catObj, "upperBound") <- value validObject(catObj) return(catObj) }) setGeneric("setEstimation<-", function(catObj, value) standardGeneric("setEstimation<-")) setReplaceMethod("setEstimation", "Cat", definition = function(catObj, value){ slot(catObj, "estimation") <- value validObject(catObj) return(catObj) }) setGeneric("setEstimationDefault<-", function(catObj, value) standardGeneric("setEstimationDefault<-")) setReplaceMethod("setEstimationDefault", "Cat", definition = function(catObj, value){ slot(catObj, "estimationDefault") <- value validObject(catObj) return(catObj) }) setGeneric("setSelection<-", function(catObj, value) standardGeneric("setSelection<-")) setReplaceMethod("setSelection", "Cat", definition = function(catObj, value){ slot(catObj, "selection") <- value validObject(catObj) return(catObj) }) setGeneric("setZ<-", function(catObj, value) standardGeneric("setZ<-")) setReplaceMethod("setZ", "Cat", definition = function(catObj, value){ slot(catObj, "z") <- value validObject(catObj) return(catObj) }) setGeneric("setLengthThreshold<-", function(catObj, value) standardGeneric("setLengthThreshold<-")) setReplaceMethod("setLengthThreshold", "Cat", definition = function(catObj, value){ slot(catObj, "lengthThreshold") <- value validObject(catObj) return(catObj) }) setGeneric("setSeThreshold<-", function(catObj, value) standardGeneric("setSeThreshold<-")) setReplaceMethod("setSeThreshold", "Cat", definition = function(catObj, value){ slot(catObj, "seThreshold") <- value validObject(catObj) return(catObj) }) setGeneric("setGainThreshold<-", function(catObj, value) standardGeneric("setGainThreshold<-")) setReplaceMethod("setGainThreshold", "Cat", definition = function(catObj, value){ slot(catObj, "gainThreshold") <- value validObject(catObj) return(catObj) }) setGeneric("setInfoThreshold<-", function(catObj, value) standardGeneric("setInfoThreshold<-")) setReplaceMethod("setInfoThreshold", "Cat", definition = function(catObj, value){ slot(catObj, "infoThreshold") <- value validObject(catObj) return(catObj) }) setGeneric("setLengthOverride<-", function(catObj, value) standardGeneric("setLengthOverride<-")) setReplaceMethod("setLengthOverride", "Cat", definition = function(catObj, value){ slot(catObj, "lengthOverride") <- value validObject(catObj) return(catObj) }) setGeneric("setGainOverride<-", function(catObj, value) standardGeneric("setGainOverride<-")) setReplaceMethod("setGainOverride", "Cat", definition = function(catObj, value){ slot(catObj, "gainThreshold") <- value validObject(catObj) return(catObj) }) NULL setGeneric("getModel", function(catObj) standardGeneric("getModel")) setMethod("getModel", "Cat", function(catObj) return(catObj@model)) setGeneric("getGuessing", function(catObj) standardGeneric("getGuessing")) setMethod("getGuessing", "Cat", function(catObj) return(catObj@guessing)) setGeneric("getDiscrimination", function(catObj) standardGeneric("getDiscrimination")) setMethod("getDiscrimination", "Cat", function(catObj) return(catObj@discrimination)) setGeneric("getDifficulty", function(catObj) standardGeneric("getDifficulty")) setMethod("getDifficulty", "Cat", function(catObj) return(catObj@difficulty)) setGeneric("getAnswers", function(catObj) standardGeneric("getAnswers")) setMethod("getAnswers", "Cat", function(catObj) return(catObj@answers)) setGeneric("getIds", function(catObj) standardGeneric("getIds")) setMethod("getIds", "Cat", function(catObj) return(catObj@ids)) setGeneric("getPriorName", function(catObj) standardGeneric("getPriorName")) setMethod("getPriorName", "Cat", function(catObj) return(catObj@priorName)) setGeneric("getPriorParams", function(catObj) standardGeneric("getPriorParams")) setMethod("getPriorParams", "Cat", function(catObj) return(catObj@priorParams)) setGeneric("getLowerBound", function(catObj) standardGeneric("getLowerBound")) setMethod("getLowerBound", "Cat", function(catObj) return(catObj@lowerBound)) setGeneric("getUpperBound", function(catObj) standardGeneric("getUpperBound")) setMethod("getUpperBound", "Cat", function(catObj) return(catObj@upperBound)) setGeneric("getEstimation", function(catObj) standardGeneric("getEstimation")) setMethod("getEstimation", "Cat", function(catObj) return(catObj@estimation)) setGeneric("getEstimationDefault", function(catObj) standardGeneric("getEstimationDefault")) setMethod("getEstimationDefault", "Cat", function(catObj) return(catObj@estimationDefault)) setGeneric("getSelection", function(catObj) standardGeneric("getSelection")) setMethod("getSelection", "Cat", function(catObj) return(catObj@selection)) setGeneric("getZ", function(catObj) standardGeneric("getZ")) setMethod("getZ", "Cat", function(catObj) return(catObj@z)) setGeneric("getLengthThreshold", function(catObj) standardGeneric("getLengthThreshold")) setMethod("getLengthThreshold", "Cat", function(catObj) return(catObj@lengthThreshold)) setGeneric("getSeThreshold", function(catObj) standardGeneric("getSeThreshold")) setMethod("getSeThreshold", "Cat", function(catObj) return(catObj@seThreshold)) setGeneric("getInfoThreshold", function(catObj) standardGeneric("getInfoThreshold")) setMethod("getInfoThreshold", "Cat", function(catObj) return(catObj@infoThreshold)) setGeneric("getGainThreshold", function(catObj) standardGeneric("getGainThreshold")) setMethod("getGainThreshold", "Cat", function(catObj) return(catObj@gainThreshold)) setGeneric("getLengthOverride", function(catObj) standardGeneric("getLengthOverride")) setMethod("getLengthOverride", "Cat", function(catObj) return(catObj@lengthOverride)) setGeneric("getGainOverride", function(catObj) standardGeneric("getGainOverride")) setMethod("getGainOverride", "Cat", function(catObj) return(catObj@gainOverride) )
gauge_color <- function(g2, colors = NULL, callback = NULL){ opts <- list(colors = colors, callback = callback) make_scale(g2, vars = opts, method = "color") } gauge_color_viridis <- function(g2, option = c("viridis", "magma", "plasma", "inferno", "cividis"), reverse = FALSE, callback = NULL){ colors <- get_viridis_color(match.arg(option), reverse) opts <- list(colors = colors, callback = callback) make_scale(g2, vars = opts, method = "color") } get_viridis_color <- function(opts, rev = FALSE){ viridis <- c(" " magma <- c(" " inferno <- c(" " plasma <- c(" " cividis <- c(" " color <- viridis if(opts == "magma") color <- magma else if(opts == "inferno") color <- inferno else if(opts == "plasma") color <- plasma else if(opts == "cividis") color <- cividis if(rev) color <- rev(color) return(color) } gauge_size <- function(g2, range = NULL, callback = NULL){ opts <- list(range = range, callback = callback) make_scale(g2, vars = opts, method = "size") } gauge_opacity <- function(g2, callback = NULL){ opts <- list(callback = callback) make_scale(g2, vars = opts, method = "opacity") } gauge_shape <- function(g2, shapes = NULL, callback = NULL){ opts <- list(shapes = shapes, callback = callback) make_scale(g2, vars = opts, method = "shape") } gauge_label <- function(g2, ..., callback = NULL){ opts <- list(callback = callback, cfg = list(...)) make_scale(g2, vars = opts, method = "label") } gauge_style <- function(g2, ...){ opts <- list(cfg = list(...)) make_scale(g2, vars = opts, method = "style") } gauge_tooltip <- function(g2, callback = NULL){ make_scale(g2, vars = list(callback = callback), method = "tooltip") } make_scale <- function(g2, vars, method = "color"){ vars <- vars[lapply(vars, length) > 0] g2$x$scales[[method]] <- vars return(g2) }
library(random) options(SweaveHooks=list(twofig=function() {par(mfrow=c(1,2))}, twofig2=function() {par(mfrow=c(2,1))}, onefig=function() {par(mfrow=c(1,1))})) if ( !(file.exists("random.Rdata")) ) { randomOrg <- randomNumbers(n=5000, min=1, max=1e6, col=2)/1e6 save(randomOrg, file="random.Rdata") } else { load("random.Rdata") } summary(randomOrg) apply(randomOrg, 2, function(X) quantile(X,c(0.01, 0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95, 0.99), digits=4)) getOption("SweaveHooks")[["twofig"]]() plot(randomOrg, ylab="", xlab="", main="5000 random,org U(0,1) draws", pch='.') hist(matrix(randomOrg, ncol=1), xlab = "", ylab = "", main="Histogram")
findLogMargLik <- function (data, tData, graph, dimens, tools) { cliques <- maximal.cliques (graph) nCliques <- length(cliques) separators <- minimal.st.separators (graph) nSeparators <- length(separators) m <- multiplicity (graph, cliques, separators, tools) alpha <- tools$alpha term1 <- 0 term2 <- 0 for (i in 1:nCliques) { margFreqs <- findMargFreqs (data, tData, cliques[[i]], dimens) nMargFreqs <- length(margFreqs) term1 <- term1 + sum(lgamma(margFreqs + alpha / nMargFreqs)) term2 <- term2 + nMargFreqs * lgamma (alpha / nMargFreqs) } for (i in 1:nSeparators) if (length(separators[[i]]) > 0) { margFreqs <- findMargFreqs (data, tData, separators[[i]], dimens) nMargFreqs <- length(margFreqs) term1 <- term1 - m[i] * sum(lgamma(margFreqs + alpha / nMargFreqs)) term2 <- term2 - m[i] * nMargFreqs * lgamma (alpha / nMargFreqs) } else { term1 <- term1 - m[i] * lgamma(sum(data$freq) + alpha) term2 <- term2 - m[i] * lgamma(alpha) } return(term1 - term2) }
context("test-snpclip") test_that("snpclip throws an error w/ bad rsID", { skip_on_cran() expect_error(SNPclip(c("rs3", "rs4", "148890987"), "YRI", 0.1, "0.01", token = Sys.getenv("LDLINK_TOKEN"))) }) test_that("snpclip throws an error", { skip_on_cran() expect_named(SNPclip(c("rs3", "rs4", "rs148890987"), "YRI", 0.1, "0.01", token = Sys.getenv("LDLINK_TOKEN"))) }) test_that("snpclip works", { skip_on_cran() expect_named(SNPclip(c("rs3", "rs4", "rs148890987"), "YRI", "0.1", "0.01", token = Sys.getenv("LDLINK_TOKEN"))) }) test_that("snpclip works w/ gen coord & no threshold", { skip_on_cran() expect_named(SNPclip(c("chr13:32446842", "Rs4", "rs148890987"), "YRI", token = Sys.getenv("LDLINK_TOKEN"))) })
byf.hist <- function(formula,data,sep=FALSE,density=TRUE,xlab=NULL,ylab=NULL,col=NULL) { if (missing(formula)||(length(formula)!=3)) {stop("missing or incorrect formula")} m <- match.call(expand.dots=FALSE) m$sep <- m$density <- m$col <- NULL if (is.matrix(eval(m$data,parent.frame()))) {m$data <- as.data.frame(m$data)} m[[1]] <- as.name("model.frame") m$... <- m$xlab <- m$ylab <- NULL mf <- eval(m,parent.frame()) dname <- c(names(mf)[1],paste(names(mf)[2:ncol(mf)],collapse=":")) resp <- mf[,1] fact <- interaction(mf[,2:ncol(mf)],sep=":") nlev <- nlevels(fact) if (is.null(xlab)) {xlab <- dname[1]} if (is.null(ylab)) {ylab <- "Density"} if (sep) { opar <- par(no.readonly=TRUE) on.exit(par(opar)) par(mfrow=grDevices::n2mfrow(nlevels(fact))) if (density) { if (is.null(col)) {col <- rep("black",nlev)} if (length(col)==1) {col <- rep(col,nlev)} for (i in 1:nlev) { y <- resp[as.numeric(fact)==i] h <- suppressWarnings(hist(y,freq=FALSE,plot=FALSE)) plot(0,xlim=range(h$breaks),ylim=c(0,max(h$density)),xlab=xlab, ylab=ylab,main=levels(fact)[i],cex=0) dens <- density(y) col2 <- grDevices::col2rgb(col[i]) col3 <- grDevices::rgb(col2[1,],col2[2,],col2[3,],alpha=0.4*255,maxColorValue=255) polygon(dens$x,dens$y,col=col3,border=NA) rug(y,col=i) } } else { if (is.null(col)) {col <- rep("white",nlev)} if (length(col)==1) {col <- rep(col,nlev)} for (i in 1:nlevels(fact)) { y <- resp[as.numeric(fact)==i] hist(y,xlab=xlab,main=levels(fact)[i],col=col[i]) } } } else { if (density) { if (is.null(col)) {col <- 1:nlev} if (length(col)==1) {col <- rep(col,nlev)} dhist(resp,fac=fact,col=col,legend=TRUE,pos.legend="topright",xlab=xlab,ylab=ylab) } else { if (is.null(col)) {col <- rep(grDevices::palette(),nlev%/%length(grDevices::palette())+1)[1:nlev]} if (length(col)==1) {col <- rep(col,nlev)} angles <- seq(20,160,140/(nlev-1)) dens <- integer(nlev) for (i in 1:nlev) { x.i <- resp[as.numeric(fact)==i] dens[i] <- max(hist(x.i,plot=FALSE)$counts) } x.1 <- resp[as.numeric(fact)==1] hist(x.1,xlab=xlab,ylab=ylab,density=10,angle=angles[1],col=col[1], xlim=range(resp),ylim=c(0,max(dens)),main="") box() for (i in 2:nlev) { x.i <- resp[as.numeric(fact)==i] hist(x.i,xlab="",ylab="",main="",density=10,angle=angles[i],col=col[i], add=TRUE) } legend("topright",levels(fact),fill=col) } } }
foo <- packageDescription("citbcmst") library(citbcmst) data(citbcmst) summary(citbcmst) load(list.files(system.file("extdata", package="citbcmst"), full.names=TRUE)[1]) exp.annot.bertheau07 <- data.frame(id=rownames(exp.norm.bertheau07), stringsAsFactors=F, row.names=rownames(exp.norm.bertheau07) ) citbcmst.bertheau07 <- cit.assignBcmst( data=exp.norm.bertheau07, data.annot=exp.annot.bertheau07, data.colId="id", data.colMap="id" , citbcmst.colMap="Probe.Set.ID", dist.method="dlda", plot=TRUE ) str(citbcmst.bertheau07) table(citbcmst.bertheau07$citbcmst) table(citbcmst.bertheau07$citbcmst.mixte) table(citbcmst.bertheau07$citbcmst.core) table(citbcmst.bertheau07$citbcmst.confidence) citbcmst.bertheau07 <- cit.assignBcmst( data=exp.norm.bertheau07, data.annot=exp.annot.bertheau07, data.colId="id", data.colMap="id" , citbcmst.colMap="Probe.Set.ID", dist.method="dlda", plot=TRUE ) load(list.files(system.file("extdata", package="citbcmst"), full.names=TRUE)[2]) exp.annot.chanrion08 <- data.frame(id=rownames(exp.norm.chanrion08), gs=rownames(exp.norm.chanrion08), stringsAsFactors=F, row.names=rownames(exp.norm.chanrion08) ) citbcmst.chanrion08 <- cit.assignBcmst( data=exp.norm.chanrion08, data.annot=exp.annot.chanrion08, data.colId="id", data.colMap="gs" , citbcmst.colMap="Gene.Symbol", dist.method="pearson", plot=TRUE ) str(citbcmst.chanrion08) table(citbcmst.chanrion08$citbcmst) table(citbcmst.chanrion08$citbcmst.mixte) table(citbcmst.chanrion08$citbcmst.core) table(citbcmst.chanrion08$citbcmst.confidence) citbcmst.chanrion08 <- cit.assignBcmst( data=exp.norm.chanrion08, data.annot=exp.annot.chanrion08, data.colId="id", data.colMap="gs" , citbcmst.colMap="Gene.Symbol", dist.method="pearson", plot=TRUE )
tidy.lsmobj <- function(x, conf.int = FALSE, conf.level = .95, ...) { tidy_emmeans(x, infer = c(conf.int, TRUE), level = conf.level, ...) } tidy.ref.grid <- function(x, conf.int = FALSE, conf.level = .95, ...) { tidy_emmeans(x, infer = c(conf.int, TRUE), level = conf.level, ...) } tidy.emmGrid <- function(x, conf.int = FALSE, conf.level = .95, ...) { tidy_emmeans(x, infer = c(conf.int, TRUE), level = conf.level, ...) } tidy.summary_emm <- function(x, null.value = NULL, ...) { tidy_emmeans_summary(x, null.value = null.value) } tidy_emmeans <- function(x, ...) { s <- summary(x, ...) if (".offset." %in% colnames(x@grid)) { null.value <- x@grid[, ".offset."] } else { null.value <- 0 } term_names <- names(x@misc$orig.grid) tidy_emmeans_summary(s, null.value = null.value, term_names = term_names) } tidy_emmeans_summary <- function(x, null.value = NULL, term_names = NULL) { ret <- as.data.frame(x) repl <- list( "lsmean" = "estimate", "emmean" = "estimate", "pmmean" = "estimate", "prediction" = "estimate", "effect.size" = "estimate", "SE" = "std.error", "lower.CL" = "conf.low", "asymp.LCL" = "conf.low", "upper.CL" = "conf.high", "asymp.UCL" = "conf.high", "z.ratio" = "statistic", "t.ratio" = "statistic", "F.ratio" = "statistic", "df1" = "num.df", "df2" = "den.df", "model term" = "term" ) mc_adjusted <- any( grepl( "conf-level adjustment|p value adjustment", attr(x, "mesg"), ignore.case = TRUE ) ) if (mc_adjusted) { repl <- c(repl, "p.value" = "adj.p.value") } colnames(ret) <- dplyr::recode(colnames(ret), !!!(repl)) if ("contrast" %in% colnames(ret)) { if (length(null.value) < nrow(ret)) null.value <- rep_len(null.value, nrow(ret)) ret <- bind_cols(contrast = ret[, "contrast"], null.value = null.value, select(ret, -contrast)) } if ("term" %in% colnames(ret)) { ret <- ret %>% mutate(term = stringr::str_trim(term)) } else if (!is.null(term_names)) { term <- term_names[!term_names %in% colnames(ret)] if (length(term) != 0) { term <- paste(term_names[!term_names %in% colnames(ret)], collapse = "*") %>% rep_len(nrow(ret)) } else { term <- apply(ret, 1, function(x) colnames(ret)[which(x == ".")]) } ret <- bind_cols(ret[, colnames(ret) %in% term_names, drop = FALSE], term = term, ret[, !colnames(ret) %in% term_names, drop = FALSE]) } as_tibble(ret) %>% mutate_if(is.factor, as.character) }
hdist <- function(x, y, ...) UseMethod("hdist") hdist.sfc <- function(x, y, method="rghosh", gres=5, ditself=FALSE, maxsample=2.5e4, proj=NULL, parallel=FALSE, cores=NULL, verbose=TRUE, ...){ method <- match.arg(method,c("ghosh","rghosh","points","centroids","combined"),several.ok = FALSE) if(missing(proj)){ if(!identical(st_crs(x),st_crs(y))) stop("x and y do not use the same coordinate reference system.") if(is.na(st_crs(x)$input)){stop("Don't know how to compute distances because no coordinate reference system was found. Define a coordinate reference system (using st_crs()) or define 'proj' argument.")} if(st_crs(x)$input=="EPSG:4326"){proj=FALSE}else{proj=TRUE} } if(method=="ghosh"){ if(!(all(st_geometry_type(x) == c("POLYGON")) & all(st_geometry_type(y) == c("POLYGON")))) stop("Geometry type has to be a POLYGON if method 'rghosh' is used.") if(verbose) cat("Sampling the catchments at a resolution of about",gres,"pts/km2\n") size <- round(units::set_units(gres,"1/km^2")*units::set_units(st_area(st_union(c(x,y))),"km^2")) xydisc <- st_sample(st_union(c(x,y)),size=units::drop_units(size),type="regular") xdisc <- list() ydisc <- list() for(i in 1:length(x)) xdisc[[i]] <- xydisc[x[i]] for(i in 1:length(y)) ydisc[[i]] <- xydisc[y[i]] if(identical(x,y)){ for(i in 1:length(xdisc)) if(length(xdisc[[i]])>maxsample){ xdisc[[i]] <- ydisc[[i]] <- xdisc[[i]][sort(sample.int(length(xdisc[[i]]), size = maxsample, replace = FALSE))] if(verbose) cat("Random resampling of catchment",i,"with a maximum size sample of",maxsample,"points.\n")} }else{ for(i in 1:length(xdisc)){ if(length(xdisc[[i]])>maxsample){ xdisc[[i]] <- xdisc[[i]][sort(sample.int(length(xdisc[[i]]), size = maxsample, replace = FALSE))] if(verbose) cat("Random resampling of catchment x[",i,"] with a maximum size sample of ",maxsample," points.\n",sep="")} } for(i in 1:length(ydisc)){ if(length(ydisc[[i]])>maxsample){ ydisc[[i]] <- ydisc[[i]][sort(sample.int(length(ydisc[[i]]), size = maxsample, replace = FALSE))] if(verbose) cat("Random resampling of catchment y[",i,"] with a maximum size sample of ",maxsample," points.\n",sep="")} } } if(verbose) cat("Computing Ghosh distance between catchments\n") if(parallel){ if(missing(cores)|is.null(cores)) cores=parallel::detectCores() cl <- parallel::makeCluster(cores) doParallel::registerDoParallel(cl=cl) on.exit(parallel::stopCluster(cl)) if(!identical(x,y)){ res <- foreach::"%dopar%"(foreach::foreach(i=1:length(x),.packages="sf"), sapply(ydisc,FUN=function(x){.Fortran("gdist",coord1=st_coordinates(x),coord2=st_coordinates(xdisc[[i]]),n1=length(x),n2=length(xdisc[[i]]),proj=proj,rescale=FALSE,diag=FALSE,mdist=0)$mdist})) gdist <- matrix(unlist(res), nrow = length(x), ncol = length(y), byrow = TRUE) }else{ res <- foreach::"%dopar%"(foreach::foreach(i=1:length(x),.packages="sf"),{ tmp <- sapply(ydisc[i:length(x)],FUN=function(x){.Fortran("gdist",coord1=st_coordinates(x),coord2=st_coordinates(xdisc[[i]]),n1=length(x),n2=length(xdisc[[i]]),proj=proj,rescale=FALSE,diag=FALSE,mdist=0)$mdist}) c(rep(NA,i-1),tmp) }) gdist <- matrix(unlist(res), nrow = length(x), ncol = length(y), byrow = TRUE) for(i in 1:length(x)) gdist[,i] <- gdist[i,] } }else{ gdist <- matrix(NA,nrow=length(x),ncol=length(y)) if(!identical(x,y)){ for(i in 1:length(x)) gdist[i,] <- sapply(ydisc,FUN=function(x){.Fortran("gdist",coord1=st_coordinates(x),coord2=st_coordinates(xdisc[[i]]),n1=length(x),n2=length(xdisc[[i]]),proj=proj,rescale=FALSE,diag=FALSE,mdist=0)$mdist}) }else{ for(i in 1:length(x)) gdist[i,i:length(x)] <- gdist[i:length(x),i] <- sapply(ydisc[i:length(x)],FUN=function(x){.Fortran("gdist",coord1=st_coordinates(x),coord2=st_coordinates(xdisc[[i]]),n1=length(x),n2=length(xdisc[[i]]),proj=proj,rescale=FALSE,diag=FALSE,mdist=0)$mdist}) } } if(ditself){ if(verbose) cat(paste0("Computing Ghosh distance within catchments\n")) if(!identical(x,y)){ gdist <- cbind(gdist,sapply(xdisc,FUN=function(x){.Fortran("gdist",coord1=st_coordinates(x),coord2=st_coordinates(x),n1=length(x),n2=length(x),proj=proj,rescale=FALSE,diag=TRUE,mdist=0)$mdist})) gdist <- rbind(gdist,c(sapply(ydisc,FUN=function(x){.Fortran("gdist",coord1=st_coordinates(x),coord2=st_coordinates(x),n1=length(x),n2=length(x),proj=proj,rescale=FALSE,diag=TRUE,mdist=0)$mdist}),NA)) }else{ gdist <- cbind(gdist,diag(gdist)) gdist <- rbind(gdist,c(diag(gdist),NA)) } } units(gdist) <- units(st_distance(xdisc[[1]][1],ydisc[[1]][1])) return(gdist) } if(method=="rghosh"){ gdist <- hdist(x=x, y=y, method="ghosh", gres=gres, ditself=TRUE, maxsample=maxsample, proj=proj, parallel=parallel, cores=cores) if(verbose) cat("Rescaling Ghosh distance\n") rgdist <- matrix(NA,nrow=length(x),ncol=length(y)) if(identical(x,y)){ for(i in 1:length(x)){ for(j in 1:i){ rgdist[i,j] <- gdist[i,j]-0.5*(gdist[i,length(y)+1]+gdist[length(x)+1,j]) rgdist[j,i] <- rgdist[i,j] } } }else{ for(i in 1:length(x)){ for(j in 1:length(y)){ rgdist[i,j] <- gdist[i,j]-0.5*(gdist[i,length(y)+1]+gdist[length(x)+1,j]) } } } units(rgdist) <- units(gdist) return(rgdist) } if(method=="points"){ if(!all(st_geometry_type(x) == c("POINT") & st_geometry_type(y) == c("POINT"))) stop("Geometry type has to be a POINT if method 'points' is used.") mdist <- st_distance(x,y) return(mdist) } if(method=="centroids"){ if(!all(st_geometry_type(x) == c("POLYGON") & st_geometry_type(y) == c("POLYGON"))) stop("Geometry type has to be a POLYGON if method 'centroids' is used.") mdist <- hdist(x=st_centroid(x), y=st_centroid(y), method="points") return(mdist) } if(method=="combined") stop("The class of 'x' and 'y' has to be 'transfR' if method 'combined' is used.") } hdist.sf <- function(x, y, ...){ mdist <- hdist(x=st_geometry(x), y=st_geometry(y), ...) return(mdist) } hdist.stars <- function(x, y, ...){ mdist <- hdist(x=st_geometry(x), y=st_geometry(y), ...) return(mdist) } hdist.transfR <- function(x, y, method="rghosh", weightO=0.8, weightC=0.2, ...){ if(method=="combined"){ if(!"outlet"%in%names(x)) stop("Outlet attribute is missing in 'x' argument. See as_transfr().") if(!"outlet"%in%names(y)) stop("Outlet attribute is missing in 'y' argument. See as_transfr().") if(!"centroid"%in%names(x)) stop("Centroid attribute is missing in 'x' argument. See as_transfr().") if(!"centroid"%in%names(y)) stop("Centroid attribute is missing in 'y' argument. See as_transfr().") odist <- hdist(x$outlet, y$outlet, method = "points", ...) cdist <- hdist(x$centroid, y$centroid, method = "points", ...) mdist <- odist*weightO + cdist*weightC }else{ if(!"st"%in%names(x)) stop("Spatio-temporal arrays (st) of class stars is missing in 'x' argument. See as_transfr().") if(!"st"%in%names(y)) stop("Spatio-temporal arrays (st) of class stars is missing in 'y' argument. See as_transfr().") mdist <- hdist(x=x$st, y=y$st, ...) } return(mdist) }
PDI_validation <- function(lcp, comparison, reverse = FALSE) { if (!inherits(lcp, "SpatialLines")) { stop("lcp argument is invalid. Expecting SpatialLines* object") } if (!inherits(comparison, "SpatialLines")) { stop("Comparison argument is invalid. Expecting a SpatialLines* object") } lcp_pts <- methods::as(lcp, "SpatialPoints") comparison_pts <- methods::as(comparison, "SpatialPoints") lcp_coords <- sp::coordinates(lcp_pts) comparison_coords <- sp::coordinates(comparison_pts) lcp_coords <- base::unname(lcp_coords) comparison_coords <- base::unname(comparison_coords) if (reverse) { lcp_coords[1, ] <- comparison_coords[1, ] lcp_coords[nrow(lcp_coords), ] <- comparison_coords[nrow(comparison_coords), ] comparison_coords <- comparison_coords[nrow(comparison_coords):1, ] } else { lcp_coords[1, ] <- comparison_coords[nrow(comparison_coords), ] lcp_coords[nrow(lcp_coords), ] <- comparison_coords[1, ] } start <- lcp_coords[1, ] end <- lcp_coords[base::nrow(lcp_coords), ] coords <- base::rbind(lcp_coords, comparison_coords) p = sp::Polygon(coords) ps = sp::Polygons(list(p), 1) sps = sp::SpatialPolygons(list(ps), proj4string = crs(comparison)) if (!suppressWarnings(rgeos::gIsValid(sps))) { if (any(identical(coordinates(lcp), coordinates(comparison)), identical(lcp_coords, comparison_coords[nrow(comparison_coords):1, ]))) { sps <- as(sps, "SpatialLines") } else { sps <- rgeos::gPolygonize(rgeos::gNode(rgeos::gBoundary(sps))) sps <- rgeos::gUnaryUnion(spgeom = sps) } } PDI_area <- rgeos::gArea(sps, byid = FALSE) max_distance <- raster::pointDistance(p1 = start, p2 = end, type = "Euclidean", lonlat = FALSE) PDI <- PDI_area/max_distance sps$area <- PDI_area sps$PDI <- PDI sps$max_distance <- max_distance norm_PDI <- (PDI_area/max_distance)/max_distance * 100 sps$normalised_PDI <- norm_PDI return(sps) }
NULL setMethod("TableFilter", c("ANY", "missing"), function(object) {as(object, ".tableFilter")}) setMethod("TableFilter", c(".query", "missing"), function(object) { object@filters }) setMethod("TableFilter", c(".query", "ANY"), function(object, value) { use_class <- class(object@filters) object@filters <- as(value, use_class) validObject(object) object }) setMethod( f = "TableFilter<-", signature = c(".query", "ANY"), definition = function(object, value) { value <- switch( class(object), "gaQuery" = as(value, "gaFilter"), "rtQuery" = as(value, "rtFilter"), "mcfQuery" = as(value, "mcfFilter") ) object@filters <- value validObject(object) object } )
BIC.GNARfit <- function(object,...){ stopifnot(is.GNARfit(object)) nnodes.in <- object$frbic$nnodes alphas.in <- object$frbic$alphas.in betas.in <- object$frbic$betas.in fact.var <- object$frbic$fact.var tot.time <- object$frbic$time.in globalalpha <- object$frbic$globalalpha dotarg <- list(...) if(length(dotarg)!=0){ if(!is.null(names(dotarg))){ warning("... not used here, input(s) ", paste(names(dotarg), collapse=", "), " ignored") }else{ warning("... not used here, input(s) ", paste(dotarg, collapse=", "), " ignored") } } if(!is.null(fact.var)){ f.in <- length(unique(fact.var)) }else{ f.in <- 1 } stopifnot(is.logical(globalalpha)) stopifnot(length(nnodes.in)==1) stopifnot(floor(nnodes.in)==nnodes.in) stopifnot(tot.time != 0) tmp.resid <- residToMat(GNARobj=object, nnodes=nnodes.in)$resid tmp.resid[is.na(tmp.resid)] <- 0 larg <- det((1/tot.time) * t(tmp.resid) %*% tmp.resid) stopifnot(larg != 0) tmp1 <- log(larg) if(globalalpha){ tmp2 <- f.in * ( alphas.in + sum(betas.in) ) * log(tot.time) / tot.time }else{ tmp2 <- ( ncol(tmp.resid) * alphas.in + sum(betas.in) ) * log(tot.time) / tot.time } return(tmp1 + tmp2) }
context("test-mbl") test_that("mbl works", { nirdata <- data("NIRsoil", package = "prospectr") Xu <- NIRsoil$spc[!as.logical(NIRsoil$train), ] Yu <- NIRsoil$CEC[!as.logical(NIRsoil$train)] Yr <- NIRsoil$CEC[as.logical(NIRsoil$train)] Xr <- NIRsoil$spc[as.logical(NIRsoil$train), ] Xu <- Xu[!is.na(Yu), ][1:20, ] Xr <- Xr[!is.na(Yr), ][1:40, ] Yu <- Yu[!is.na(Yu)][1:20] Yr <- Yr[!is.na(Yr)][1:40] k_test <- seq(25, 35, by = 10) k_diss_test <- 0.1 k_range_test <- c(15, 30) ctrl_1 <- mbl_control( validation_type = c("NNv", "local_cv"), number = 4, p = 0.5, allow_parallel = FALSE ) gpr <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_gpr(), control = ctrl_1, verbose = FALSE ) pls <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_pls(5), control = ctrl_1, verbose = FALSE ) mpls <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_pls(5, modified = TRUE), control = ctrl_1, verbose = FALSE ) wapls <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_wapls(3, 5), control = ctrl_1, verbose = FALSE ) wampls <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_wapls(3, 5, modified = TRUE), control = ctrl_1, verbose = FALSE ) gpr_k_diss <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k_diss = k_diss_test, k_range = k_range_test, method = local_fit_gpr(), control = ctrl_1, verbose = FALSE ) pls_k_diss <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k_diss = k_diss_test, k_range = k_range_test, method = local_fit_pls(5), control = ctrl_1, verbose = FALSE ) wapls_k_diss <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k_diss = k_diss_test, k_range = k_range_test, method = local_fit_wapls(3, 5), control = ctrl_1, verbose = FALSE ) group_test <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_pls(5), control = ctrl_1, group = rep(c(1, 2), length.out = nrow(Xr)), verbose = FALSE ) output_names <- names(gpr) expected_names <- c( "call", "cntrl_param", "dissimilarities", "Xu_neighbors", "n_predictions", "gh", "validation_results", "results", "documentation" ) expect_is(gpr, "list") expect_is(pls, "list") expect_is(wapls, "list") expect_is(mpls, "list") expect_is(wampls, "list") expect_is(gpr_k_diss, "list") expect_is(pls_k_diss, "list") expect_is(wapls_k_diss, "list") expect_is(group_test, "list") expect_true(all(expected_names %in% output_names)) }) test_that("mbl delivers expeted results", { skip_on_cran() skip_on_travis() require(prospectr) nirdata <- data("NIRsoil", package = "prospectr") NIRsoil$spc <- prospectr::savitzkyGolay(NIRsoil$spc, p = 3, w = 11, m = 0) Xu <- NIRsoil$spc[!as.logical(NIRsoil$train), ] Yu <- NIRsoil$CEC[!as.logical(NIRsoil$train)] Yr <- NIRsoil$CEC[as.logical(NIRsoil$train)] Xr <- NIRsoil$spc[as.logical(NIRsoil$train), ] Xu <- Xu[!is.na(Yu), ] Xr <- Xr[!is.na(Yr), ] Yu <- Yu[!is.na(Yu)] Yr <- Yr[!is.na(Yr)] ctrl_1 <- mbl_control( validation_type = c("NNv", "local_cv"), number = 4, p = 0.8, tune_locally = TRUE, allow_parallel = FALSE ) k_test <- c(40, 150) k_diss_test <- 0.1 k_range_test <- c(20, 100) pls_wapls <- c(3, 15) pls_pls <- c(10) grpnoisevar <- 0.0001 tseed <- 141020 set.seed(tseed) gpr <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_gpr(grpnoisevar), control = ctrl_1, verbose = FALSE ) set.seed(tseed) pls <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_pls(pls_pls), control = ctrl_1, verbose = FALSE ) set.seed(tseed) wapls <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_wapls(pls_wapls[1], pls_wapls[2]), control = ctrl_1, verbose = FALSE ) set.seed(tseed) mpls <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_pls(pls_pls, modified = TRUE), control = ctrl_1, verbose = FALSE ) set.seed(tseed) wampls <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_wapls(pls_wapls[1], pls_wapls[2], modified = TRUE), control = ctrl_1, verbose = FALSE ) set.seed(tseed) gpr_k_diss <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k_diss = k_diss_test, k_range = k_range_test, method = local_fit_gpr(), control = ctrl_1, verbose = FALSE ) set.seed(tseed) pls_k_diss <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k_diss = k_diss_test, k_range = k_range_test, method = local_fit_pls(pls_pls), control = ctrl_1, verbose = FALSE ) set.seed(tseed) wapls_k_diss <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k_diss = k_diss_test, k_range = k_range_test, method = local_fit_wapls(pls_wapls[1], pls_wapls[2]), control = ctrl_1, verbose = FALSE ) set.seed(tseed) xgroup <- rep((1:(floor(nrow(Xr) / 2))), each = 2) pls_group <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_pls(pls_pls), control = ctrl_1, group = xgroup, verbose = FALSE ) set.seed(tseed) pls_group_local <- mbl( Xr = Xr, Yr = Yr, Xu = Xu, Yu = Yu, k = k_test, method = local_fit_pls(pls_pls), control = ctrl_1, group = xgroup, .local = TRUE, pre_k = 200, verbose = FALSE ) cv_gpr <- c( gpr$validation_results$local_cross_validation$rmse < 1.8, gpr$validation_results$local_cross_validation$rmse > 1.5 ) cv_pls <- c( pls$validation_results$local_cross_validation$rmse < 1.8, pls$validation_results$local_cross_validation$rmse > 1.4 ) cv_wapls <- c( wapls$validation_results$local_cross_validation$rmse < 1.8, wapls$validation_results$local_cross_validation$rmse > 1.4 ) cv_mpls <- c( mpls$validation_results$local_cross_validation$rmse < 1.8, mpls$validation_results$local_cross_validation$rmse > 1.5 ) cv_wampls <- c( wampls$validation_results$local_cross_validation$rmse < 1.68, wampls$validation_results$local_cross_validation$rmse > 1.45 ) cv_gpr_k_diss <- c( gpr_k_diss$validation_results$local_cross_validation$rmse < 1.9, gpr_k_diss$validation_results$local_cross_validation$rmse > 1.6 ) cv_pls_k_diss <- c( pls_k_diss$validation_results$local_cross_validation$rmse < 1.7, pls_k_diss$validation_results$local_cross_validation$rmse > 1.4 ) cv_wapls_k_diss <- c( wapls_k_diss$validation_results$local_cross_validation$rmse < 2, wapls_k_diss$validation_results$local_cross_validation$rmse > 1.4 ) cv_group <- c( pls_group$validation_results$local_cross_validation$rmse < 2, pls_group$validation_results$local_cross_validation$rmse > 1.4 ) cv_group_local <- c( pls_group_local$validation_results$local_cross_validation$rmse < 2, pls_group_local$validation_results$local_cross_validation$rmse > 1 ) nnv_group_local <- pls_group_local$validation_results$nearest_neighbor_validation$r2 > 0.4 nnv_group <- pls_group$validation_results$nearest_neighbor_validation$r2 > 0.7 nnv_gpr <- gpr$validation_results$nearest_neighbor_validation$r2 > 0.81 nnv_pls <- pls$validation_results$nearest_neighbor_validation$r2 > 0.74 nnv_wapls <- wapls$validation_results$nearest_neighbor_validation$r2 > 0.80 nnv_gpr_k_diss <- gpr_k_diss$validation_results$nearest_neighbor_validation$r2 > 0.81 nnv_pls_k_diss <- pls_k_diss$validation_results$nearest_neighbor_validation$r2 > 0.81 nnv_wapls_k_diss <- wapls_k_diss$validation_results$nearest_neighbor_validation$r2 > 0.81 yuv_gpr <- gpr$validation_results$Yu_prediction_statistics$r2 > 0.72 yuv_pls <- pls$validation_results$Yu_prediction_statistics$r2 > 0.67 yuv_wapls <- wapls$validation_results$Yu_prediction_statistics$r2 > 0.69 yuv_gpr_k_diss <- gpr_k_diss$validation_results$Yu_prediction_statistics$r2 > 0.72 yuv_pls_k_diss <- pls_k_diss$validation_results$Yu_prediction_statistics$r2 > 0.60 yuv_wapls_k_diss <- wapls_k_diss$validation_results$Yu_prediction_statistics$r2 > 0.65 expect_true(all(cv_gpr)) expect_true(all(cv_pls)) expect_true(all(cv_wapls)) expect_true(all(cv_mpls)) expect_true(all(cv_wampls)) expect_true(all(cv_gpr_k_diss)) expect_true(all(cv_pls_k_diss)) expect_true(all(cv_wapls_k_diss)) expect_true(all(cv_group)) expect_true(all(cv_group_local)) expect_true(all(nnv_gpr)) expect_true(all(nnv_pls)) expect_true(all(nnv_wapls)) expect_true(all(nnv_gpr_k_diss)) expect_true(all(nnv_pls_k_diss)) expect_true(all(nnv_wapls_k_diss)) expect_true(all(nnv_group)) expect_true(all(nnv_group_local)) expect_true(all(yuv_gpr)) expect_true(all(yuv_pls)) expect_true(all(yuv_wapls)) expect_true(all(yuv_gpr_k_diss)) expect_true(all(yuv_pls_k_diss)) expect_true(all(yuv_wapls_k_diss)) })
set.seed(919) u1 = rlnorm(10) v1 = rlnorm(10) Y1 = u1%*%t(v1) u2 = rlnorm(10) v2 = rlnorm(10) Y2 = .5+u2%*%t(v2) Y_nn = rbind(Y1,Y2) Y = Y_nn + array(rlnorm(prod(dim(Y_nn)),0,.05),dim(Y_nn)) library('reshape2') library('ggplot2') group = factor(rep(c(1,2),each=nrow(Y)/2)) levels(group) = c("group1","group2") mY = melt(data.frame(Y,group),id.vars="group") ggplot(data=mY,mapping=aes(x=value,fill=group))+geom_histogram(bins=100)+geom_vline(data=aggregate(value~group,data=mY,mean),mapping=aes(xintercept=value,linetype=group),size=1.5) t.test(rowMeans(Y)[group=="group1"],rowMeans(Y)[group=="group2"]) library('rrscale') scl = rrscale(Y) scl$T_name scl$par_hat trans_Y = scl$RR trans_Y2 = scl$rr_fn(Y) all(trans_Y2==trans_Y,na.rm=TRUE) tmY = melt(data.frame(trans_Y,group),id.vars="group") ggplot(data=tmY,mapping=aes(x=value,fill=group))+geom_histogram(bins=100)+geom_vline(data=aggregate(value~group,data=tmY,mean),mapping=aes(xintercept=value,linetype=group),size=1.5) t.test(rowMeans(trans_Y)[group=="group1"],rowMeans(trans_Y)[group=="group2"]) plot(svdc(Y)$u[,1:2],col=group,xlab="PC1",ylab="PC2") plot(svdc(trans_Y)$u[,1:2],col=group,xlab="PC1",ylab="PC2") cancor(model.matrix(~1+group),svdc(Y)$u[,1:2]) cancor(model.matrix(~1+group),svdc(trans_Y)$u[,1:2])
context("stopover mass calculator") test_that("mismatch length throw error", { expect_error(stopover.mass.calculator(bodyMass = c(1.1,1.2), fatMass = c(0.34), taxon = c(1, 2), duration = 24L )) }) test_that("negaative duration throws error", { expect_error(stopover.mass.calculator(bodyMass = c(1.1,1.2), fatMass = c(0.34, 0.25), taxon = c(1, 2), duration = -24L )) }) test_that("negaative duration throws error", { expect_error(stopover.mass.calculator(bodyMass = c(1.1,1.2), fatMass = c(0.34, 0.25), taxon = c(1, 3), duration = 24L )) })
checker = function(){ R6Checker$new() } R6Checker = R6::R6Class('Checker',inherit=NULL, public=list( initialize = function(){ }, checkHasNames = function(x,objnm = deparse(substitute(x))){ `if`(!is.character(names(x)), stop(sprintf("'%s' of type ['%s'] must be a named object",objnm,paste(class(x),collapse="', '")),call.=FALSE),invisible(x)) }, checkAllNamesAreIn = function(A,B,objnmA = deparse(substitute(A)), objnmB = deparse(substitute(B))){ self$checkHasNames(A,objnmA) self$checkHasNames(B,objnmB) missing = setdiff(names(A),names(B)) `if`(length(missing) > 0,{ stop(sprintf("All names in '%s' must also be in '%s'. Missing: ['%s']", objnmA, objnmB, paste(missing,collapse=", ")), call.=FALSE) },invisible(A)) }, checkAllNamesAreUnique = function(x,objnm = deparse(substitute(A))){ self$checkHasNames(x,objnm) `if`(!identical(length(names(x)),length(unique(names(x)))), stop(sprintf("All names in '%s' must be unique.",objnm),call.=FALSE), invisible(x)) }, checkPositiveNumericScalar = function(x, includeZero = FALSE, objnm = deparse(substitute(x))){ self$checkNumericScalar(x,objnm = objnm) self$checkRange(x, 0, aop = `if`(includeZero,'>=','>'), objnm = objnm) }, checkPositiveIntegerScalar = function(x,includeZero = FALSE, objnm = deparse(substitute(x))){ self$checkLength(x,1,objnm = objnm) self$checkInteger(x,objnm=objnm) self$checkRange(x, 0, aop = `if`(includeZero,'>=','>'), objnm = objnm) }, checkNumericScalar = function(x, objnm = deparse(substitute(x))){ self$checkLength(x,1,objnm = objnm) self$checkNumeric(x,objnm = objnm) }, checkLogicalScalar = function(x,objnm = deparse(substitute(x))){ self$checkLength(x,1,objnm=objnm) self$checkLogical(x, objnm = objnm) }, checkCharacterScalar = function(x,objnm = deparse(substitute(x))){ self$checkLength(x,1,objnm = objnm) self$checkCharacter(x, objnm = objnm) }, checkScalarOfType = function(x, type = enfArg('type'), objnm = deparse(substitute(x))){ self$checkLength(x,1,objnm=objnm) self$checkClass(x,type,objnm=objnm) }, checkFractional = function(x, objnm = deparse(substitute(x))){ self$checkNumeric(x, objnm = objnm) self$checkRange(x,0,1,aop='>=',bop="<=", objnm = objnm) }, checkFractionalScalar = function(x, objnm){ self$checkScalar(x, objnm = objnm) self$checkFractional(x, objnm = objnm) }, checkNumeric = function(x,objnm = deparse(substitute(x))){ `if`(!all(is.numeric(x)), stop(sprintf("'%s' must be numeric",objnm),call.=FALSE), invisible(x)) }, checkInteger = function(x, objnm = deparse(substitute(x))){ `if`(!all(is.integer(x)) & !(all(is.numeric(x)) & all(x %% 1 == 0)), stop(sprintf("'%s' must be integer",objnm),call.=FALSE), invisible(x)) }, checkIntegerScalar = function(x, objnm = deparse(substitute(x))){ self$checkInteger(x,objnm = objnm) self$checkScalar(x,objnm = objnm) }, checkCharacter = function(x, objnm = deparse(substitute(x))){ `if`(!is.character(x), stop(sprintf("'%s' must be character",objnm),call.=FALSE), invisible(x)) }, checkLogical = function(x, objnm = deparse(substitute(x))){ `if`(!is.logical(x), stop(sprintf("'%s' must be logical",objnm),call.=FALSE), invisible(x)) }, checkClass = function(x,type = enfArg('type'), objnm = deparse(substitute(x))){ `if`(!inherits(x,type), stop(sprintf("'%s' must inherit one of ['%s']",objnm,paste(type,collapse="', '")),call.=FALSE), invisible(x)) }, checkDataFrame = function(x,objnm = deparse(substitute(x))){ self$checkClass(x,'data.frame',objnm = objnm) }, checkListOfClass = function(x, type = enfArg('type'), recursive = FALSE, objnm = deparse(substitute(x))){ self$checkCharacterScalar(type, objnm = 'type') self$checkClass(x,'list', objnm) check = sapply( `if`(recursive, flatten(x), x) , function(o){ inherits(o,type) }) `if`(!all(check), stop(sprintf("All '%s' objects must inherit from '%s'",objnm,type),call.=FALSE), invisible(x)) }, checkNumericDataFrame = function(x,objnm = deparse(substitute(x))){ self$checkDataFrame(x,objnm = objnm) `if`(!all(sapply(as.list(x),function(o)is.numeric(o))), stop(sprintf("All columns of '%s' must be numeric.",objnm),call.=FALSE), invisible(x)) }, checkLength = function(x,n = 1,op='==',objnm = deparse(substitute(x))){ self$checkIsIn(op,c('==','>','<','>=','<=')) n = as.integer(unique(n)) `if`(!{any(do.call(op,args=list(length(x),n)))}, stop(sprintf("'%s' must be of length/s '%s' ['%s']",objnm,op,paste(n,collapse="', '")),call.=FALSE), invisible(x)) }, checkScalar = function(x, objnm = deparse(substitute(x))){ self$checkLength(x,1,objnm = objnm) }, checkNotNullOrNA = function(x,objnm = deparse(substitute(x))){ `if`(is.null(x) || is.na(x),stop(sprintf("'%s' must not be NULL or NA",objnm),call.=FALSE),invisible(x)) }, checkNonZeroLength = function(x,objnm = deparse(substitute(x))){ `if`(!length(x), stop(sprintf("'%s' must not be zero length",objnm),call.=FALSE), invisible(x)) }, checkIsIn = function(x,valid = enfArg('valid'), objnm = deparse(substitute(x)),objnmB = deparse(substitute(valid))){ self$checkNonZeroLength(valid,objnm = objnmB) self$checkNotNullOrNA(valid,objnm = objnm) `if`(!all(x %in% valid), stop(sprintf("All '%s' (%s) must be in: ['%s'], missing: '%s'", objnm, paste(x,collapse="', '"), paste(valid,collapse="', '"), paste(setdiff(x,valid),collapse="', '") ),call.=FALSE), invisible(x)) }, checkAny = function(x,objnm = deparse(substitute(x))){ self$checkLogical(x,objnm=objnm) `if`(!any(x), stop(sprintf("At least one of '%s' must be TRUE.",objnm),call.=FALSE), invisible(x)) }, checkRange = function(x, a = -Inf, b = Inf, aop = '>=', bop = '<=', objnm = deparse(substitute(x))){ self$checkNumeric(x,objnm = objnm) self$checkNumeric(a,objnm = sprintf("%s (lower bound)",objnm)) self$checkNumeric(b,objnm = sprintf("%s (upper bound)",objnm)) vop = c('>','>=','<','<=','==') self$checkScalarOfType(aop,'character', objnm = objnm) self$checkIsIn(aop,vop, objnm = objmm) self$checkScalarOfType(bop,'character', objnm = objnm) self$checkIsIn(bop,vop, objnm = objmm) a = `if`(is.na(a),-Inf,a) b = `if`(is.na(b),+Inf,b) `if`(!all(do.call(aop,args=list(x,a)) & do.call(bop,args=list(x,b))), stop(sprintf("'%s' must be in the range ['%s' %s %s] AND ['%s' %s %s]", objnm, objnm,aop,a, objnm,bop,b),call.=FALSE), invisible(x)) }, checkPositive = function(x, objnm = deparse(substitute(x))){ self$checkRange(x, a = 0, aop='>', objnm = objnm) }, checkNegative = function(x, objnm = deparse(substitute(x))){ self$checkRange(x, a = 0, aop="<", objnm = objnm) } ), private=list( ) )
test_that("add_fct and add_utils", { with_dir(pkg, { util_file <- "R/utils_ui.R" fct_file <- "R/fct_ui.R" mod <- "R/mod_plop.R" remove_file(util_file) remove_file(fct_file) remove_file(mod) add_fct("ui", pkg = pkg, open = FALSE, with_test = TRUE) add_utils("ui", pkg = pkg, open = FALSE, with_test = TRUE) expect_true(file.exists(util_file)) expect_true(file.exists(fct_file)) expect_true(file.exists("tests/testthat/test-utils_ui.R")) expect_true(file.exists("tests/testthat/test-fct_ui.R")) rand <- rand_name() add_module(rand, pkg = pkg, open = FALSE) add_fct("ui", rand, pkg = pkg, open = FALSE) add_utils("ui", rand, pkg = pkg, open = FALSE) expect_true(file.exists(sprintf("R/mod_%s_fct_ui.R", rand))) expect_true(file.exists(sprintf("R/mod_%s_utils_ui.R", rand))) expect_error( add_fct("ui", module = "notyetcreated", pkg = pkg, open = FALSE), regexp = "The module 'notyetcreated' does not exist." ) expect_error( add_utils("ui", module = "notyetcreated", pkg = pkg, open = FALSE), regexp = "The module 'notyetcreated' does not exist." ) mod_ploup_file <- "R/mod_ploup.R" remove_file(mod_ploup_file) add_module("ploup", pkg = pkg, open = FALSE) add_fct("fct", module = basename(mod_ploup_file), pkg = pkg, open = FALSE) add_utils("utils", module = basename(mod_ploup_file), pkg = pkg, open = FALSE) expect_true(file.exists("R/mod_ploup_fct_fct.R")) expect_true(file.exists("R/mod_ploup_utils_utils.R")) remove_file(mod_ploup_file) remove_file("R/mod_ploup_fct_fct.R") remove_file("R/mod_ploup_utils_utils.R") remove_file(sprintf("R/mod_%s.R", rand)) remove_file(sprintf("R/mod_%s_fct_ui.R", rand)) remove_file(sprintf("R/mod_%s_utils_ui.R", rand)) }) })
"SpectraDataFrame" <- function(..., wl=numeric(), nir=matrix(), id=as.character(NA), units="nm", data=data.frame()) { dotargs <- list(...) if (any(sapply(dotargs, inherits, "Spectra"))) { id_spectra <- which(sapply(dotargs, inherits, "Spectra")) if (length(id_spectra) > 1) { ss <- dotargs[id_spectra] s <- ss[[1]] for (i in 2:length(id_spectra)) s <- rbind(s, ss[[i]]) } else s <- dotargs[[1]] wl <- wl(s) nir <- spectra(s) id <- ids(s, as.vector = FALSE) units <- wl_units(s) } else { if (is(wl, "integer")) wl <- as.numeric(wl) if (is(nir, 'data.frame')) nir <- as.matrix(nir) if (!is(id, "data.frame")) id <- data.frame(id = id) if (all(is.na(id))) { if (length(nir) == 1) id <- data.frame(NULL) else id <- data.frame(id = as.character(seq(1, nrow(nir)))) } else { if (is.null(nrow(nir))) { if (nrow(id) != 1) stop("number of individuals and number of rows in the spectra matrix don't match") if ((length(wl) > 1) & (length(nir) != length(wl))) stop("number of columns in the spectra matrix and number of observed wavelengths don't match") nir <- matrix(nir, nrow=1) } else { if (nrow(nir) != nrow(id)) stop("number of individuals and number of rows in the spectra matrix don't match") if ((length(wl) > 1) & (ncol(nir) != length(wl))) stop("number of columns in the spectra matrix and number of observed wavelengths don't match") colnames(nir) <- wl rownames(nir) <- as.vector(do.call('rbind', id)) } } } if (is(data, "numeric") | is(data, "integer")) data <- as.data.frame(data) if (!any(duplicated(id[, 1]))) { rownames(data) <- id[, 1] } else { rownames(data) <- NULL } new("SpectraDataFrame", wl=wl, nir=nir, id=id, units=units, data=data) } as.data.frame.SpectraDataFrame = function(x, ..., expand = TRUE, exclude_id = FALSE) { data <- features(x, exclude_id = exclude_id) if (expand) { df <- data.frame(data, spectra(x)) names(df) <- c(names(data), wl(x)) } else { df <- data.frame(data, NIR = I(spectra(x))) } df } setAs("SpectraDataFrame", "data.frame", function(from) { as.data.frame.SpectraDataFrame(from) }) if (!isGeneric("features")) setGeneric("features", function(object, exclude_id = TRUE) standardGeneric("features")) setMethod("features", "SpectraDataFrame", function(object, exclude_id = TRUE) { if (!exclude_id) { res <- data.frame(ids(object, as.vector = FALSE), object@data) } else { res <- object@data } res } ) if (!isGeneric('features<-')) setGeneric('features<-', function(object, value, safe = TRUE, key = NULL, exclude_id = TRUE, append = TRUE) standardGeneric('features<-') ) setReplaceMethod("features", signature("SpectraDataFrame", "ANY"), function(object, value, safe = TRUE, key = NULL, exclude_id = TRUE, append = TRUE) { if (!inherits(value, "data.frame")) stop('data must be provided as a data.frame object') if (safe) { if (is.null(key)) stop("In the safe mode, you need to provide either the column name of the sample ids to the key option.") if (length(key) != 1) stop("Please provide only ONE id column.") if (is.numeric(key)) { key <- names(value)[key] } if (append) { d <- data.frame(ids(object, as.vector = FALSE), features(object)) names(d)[1] <- key } else { d <- ids(object, as.vector = FALSE) names(d) <- key } d[[key]] <- as.character(d[[key]]) value[[key]] <- as.character(value[[key]]) data <- join(d, value, by = key, type = "left", match = "first") if (exclude_id) data <- data[, -1*which(names(data) == key), drop = FALSE] } else { warning("Sample ID check has been disabled. This mode assumes you made sure the order of the rows in your data is consistent with the order in which these samples appear in the Spectra object.") if (append) data <- data.frame(features(object), value) else data <- value } SpectraDataFrame(object, data = data) } ) setMethod("$", "SpectraDataFrame", definition=function(x, name) x@data[[name]] ) setReplaceMethod("$", "Spectra", definition=function(x, name, value) { if ('data' %in% slotNames(x)) { x@data[[name]] <- value } else { data <- data.frame(value) names(data) <- name x <- SpectraDataFrame(x, data = data) } x } ) setMethod("[[", c("SpectraDataFrame", "ANY", "missing"), function(x, i, j, ...) { if (!("data" %in% slotNames(x))) stop("no [[ method for object without attributes") x@data[[i]] } ) setReplaceMethod("[[", c("Spectra", "ANY", "missing", "ANY"), function(x, i, j, value) { if ('data' %in% slotNames(x)) { x@data[[i]] <- value } else { data <- data.frame(value) names(data) <- i x <- SpectraDataFrame(x, data = data) } x } ) setMethod("[", c("SpectraDataFrame", "ANY", "ANY", "missing"), function(x, i, j, ..., k, drop = FALSE) { .bracket <- function(x, i, j, k, ..., drop = FALSE) { missing.i <- missing(i) missing.j <- missing(j) missing.k <- missing(k) if (missing.i) { i <- TRUE } else { if (any(is.na(i))) { stop("NAs not permitted in row index") } if (is.character(i)) { i <- which(x@id %in% i) } } if (missing.j) { j <- TRUE } else { if (is.numeric(j)) { if (all(j < 0)) { j <- setdiff(1:ncol(x), abs(j)) } } else { j <- which(names(x) %in% j) } } if (missing.k) { k <- TRUE } else { if (all(k < 0)) { k <- setdiff(as.numeric(wl(x)), abs(k)) } k <- which(as.numeric(wl(x)) %in% k) } SpectraDataFrame(wl = x@wl[k], nir = x@nir[i, k, drop = FALSE], id = x@id[i, , drop = FALSE], data = features(x)[i, j, drop = FALSE]) } .bracket(x, i, j, k, ..., drop = drop) } ) names.SpectraDataFrame <- function(x) names(x@data) "names<-.SpectraDataFrame" <- function(x, value) { names(x@data) <- value x } if (!isGeneric("melt_spectra")) setGeneric("melt_spectra", function(obj, attr, ...) standardGeneric("melt_spectra")) setMethod("melt_spectra", "SpectraDataFrame", function(obj, attr = NULL, ...){ id.nm <- names(ids(obj, as.vector = FALSE)) if (!is.null(attr)) { data <- subset(features(obj), select = attr) x <- data.frame(ids(obj, as.vector = FALSE), data, spectra(obj)) names(x) <- c(id.nm, attr, wl(obj)) } else { x <- data.frame(ids(obj, as.vector = FALSE), spectra(obj)) names(x) <- c(id.nm, wl(obj)) } res <- melt(x, id.vars = c(id.nm, attr), variable.name = 'wl', value.name = "nir") res$wl <- as.numeric(as.character(res$wl)) res }) .subset.SpectraDataFrame <- function(x, subset, select, drop = FALSE, ...) { df <- features(x) if (missing(subset)) r <- TRUE else { e <- substitute(subset) r <- eval(e, df, parent.frame()) if (!is.logical(r)) stop("'subset' must evaluate to logical") r <- r & !is.na(r) } if (missing(select)) vars <- TRUE else { nl <- as.list(seq_along(df)) names(nl) <- names(df) vars <- eval(substitute(select), nl, parent.frame()) } df_sub <- df[r, vars, drop = drop] df_sub <- droplevels(df_sub) id_selected <- which(rownames(df) %in% rownames(df_sub)) SpectraDataFrame(wl = wl(x), nir = spectra(x)[id_selected, , drop = FALSE], id = ids(x, as.vector = FALSE)[id_selected, 1, drop = FALSE], units = wl_units(x), data = df_sub) } setMethod("subset", "SpectraDataFrame", .subset.SpectraDataFrame)
install.packages( 'gt.doc.images', repos = c(ddsjoberg = 'https://ddsjoberg.r-universe.dev', CRAN = 'https://cloud.r-project.org') ) gt.doc.images::save_help_file_images(pkg = "gtsummary") gt.doc.images::save_help_file_images(pkg = "gtsummary", rd_files = "as_kable_extra.Rd") gt.doc.images::shrink_help_file_images(pkg = "gtsummary") gt.doc.images::shrink_help_file_images(pkg = "gtsummary", image_files = "tbl_strata_ex1.png") c("as_kable_extra_ex2_pdf.png", "as_kable_extra_ex3_pdf.png", "as_kable_extra_ex1_pdf.png", "as_flex_table_ex1.png") |> purrr::walk(~webshot::shrink(here::here("man", "figures", .x)))
predict.IM4E<-function(object,xx,yy,newx,sig = 1, type = "both",...){ TYPES <- c("both","response","class") typeIdx <- pmatch(type, TYPES) if (is.na(typeIdx)){ stop("Invalid type") } yy<-as.numeric(yy) if (ncol(xx) != ncol(newx)){ stop("xx and newx have different lengths of explanatory variables") } if (is.list(object)){ w<-matrix(object$w) }else{ w<-object } label<-unique(yy) v<-sapply(c(1:length(label)),function(j){ sapply(c(1:nrow(newx)), function(i){ yyy<-abs(yy-label[j]) y<-rep(0,length(yyy)) y[which(yyy==0)]<-1 tmp<-matrix((y)*exp(-(t(w)%*%abs(t(xx)-as.numeric(newx[i,]))/sig) -1 )) s<-sum(tmp) if (s!=0) tmp<-tmp/s (t(w)%*%abs(t(xx)-as.numeric(newx[i,])))%*%tmp }) }) myfun<-sapply(c(1:nrow(newx)), function(i){ v[i,]<<-v[i,]/sum(v[i,]) }) pred<-sapply(c(1:nrow(newx)),function(i){ label[which.min(v[i,])] }) if (type == "both"){ newList<-list("class"=pred,"prob"=v) return(newList) }else if(type == "response"){ return(v) }else if(type == "class"){ return(pred) }else{ stop("use wrong type") } }
find_positions <- function (nams1, nams2) { nams1 <- gsub("^", "\\^", nams1, fixed = TRUE) vals <- c(glob2rx(nams1), glob2rx(paste0(nams1, ":*")), glob2rx(paste0("*:", nams1))) out <- sort(unique(unlist(lapply(vals, grep, x = nams2)))) out }