using VAR package
Applied Econometrics with R Package Vignette and Errata
Applied Econometrics with R: Package Vignette and ErrataChristian Kleiber Universit¨a t BaselAchim ZeileisWirtschaftsuniversit¨a t Wien Abstract“Applied Econometrics with R”(Kleiber and Zeileis2008,Springer-Verlag,ISBN˜978-0-387-77316-2,pp.˜vii+222)is thefirst book on applied econometrics using the R˜systemfor statistical computing and graphics(R Development Core Team2008).It presentshands-on examples for a wide range of econometric models,from classical linear regressionmodels for cross-section,time series or panel data and the common non-linear models ofmicroeconometrics,such as logit,probit,tobit models as well as regression models forcount data,to recent semiparametric extensions.In addition,it provides a chapter onprogramming,including simulations,optimization and an introduction to R tools enablingreproducible econometric research.The methods are presented by illustrating,amongother things,thefitting of wage equations,growth regressions,dynamic regressions andtime series models as well as various models of microeconometrics.The book is accompanied by the R package AER(Kleiber and Zeileis2009)which contains some new R functionality,some100data sets taken from a wide variety ofsources,the full source code for all examples used in the book,as well as further workedexamples,e.g.,from popular textbooks.This vignette provides an overview of the package contents and contains a list of errata for the book.Keywords:˜econometrics,statistical software,R.1.Package overview1.1.R code from the bookThe full R code from the book is provided in the demos for the package AER.The source scripts can be found in the demo directory of the package and executed interactively by calling demo(),as inR>demo("Ch-Intro",package="AER")One demo per chapter is provided:Ch-Intro(Chapter˜1:Introduction),Ch-Basics(Chapter˜2:Basics),2AER:Package Vignette and ErrataCh-LinearRegression(Chapter˜3:Linear Regression),Ch-Validation(Chapter˜4:Diagnostics and Alternative Methods of Regression), Ch-Microeconometrics(Chapter˜5:Models of Microeconometrics),Ch-TimeSeries(Chapter˜6:Time Series),Ch-Programming(Chapter˜7:Programming Your Own Analysis).This list of demos is also shown by demo(package="AER").The same scripts are contained in the tests directory of the package so that they are auto-matically checked and compared with the desired output provided in.Rout.savefiles.To make the code fully reproducible and to avoid some lengthy computations in the daily checks,a few selected code chunks are commented out in the scripts.Also,for technical reasons,some graphics code chunks are repeated,once commented out and once without comments.1.2.Data setsThe AER package includes some100data sets from leading applied econometrics journals and popular econometrics textbooks.Many data sets have been obtained from the data archives of the Journal of Applied Econometrics and the Journal of Business&Economic Statistics.Some of these are used in recent textbooks,among them Baltagi(2002),Davidson and MacKinnon(2004),Greene(2003),Stock and Watson(2007),and Verbeek(2004).In addition,we provide all further data sets from Baltagi(2002),Franses(1998),Greene(2003), and Stock and Watson(2007).Detailed information about the source of each data set,descriptions of the variables included, and usually also examples for typical analyses are provided on the respective manual pages.A full list of all data sets in AER can be obtained viaR>data(package="AER")In addition,manual pages corresponding to selected textbooks are available.They list all data sets from the respective book and provide extensive code for replicating many of the empirical examples.See,for example,R>help("Greene2003",package="AER")for data sets and code for Greene(2003).Currently available manual pages are: Baltagi2002for Baltagi(2002),CameronTrivedi1998for Cameron and Trivedi(1998),Franses1998for Franses(1998),Greene2003for Greene(2003),StockWatson2007for Stock and Watson(2007).Christian Kleiber,Achim Zeileis31.3.New R functionsAER provides a few new R functions extending or complementing methods previously available in R:tobit()is a convenience interface to survreg()from package survival forfitting tobit regressions to censored data.In addition to thefitting function itself,the usual set of accessor and extractor functions is provided,e.g.,print(),summary(),logLik(),etc.For more details see?tobit.ivreg()fits instrumental-variable regressions via two-stage least squares.It providesa formula interface and calls the workhorse function ivreg.fit()which in turn callslm.fit()twice.In addition to thefitting functions,the usual set of accessor and extractor functions is provided,e.g.,print(),summary(),anova(),etc.For more details see?ivreg,?ivreg.fit,and?summary.ivreg,respectively.dispersiontest()tests the null hypothesis of equidispersion in Poisson regressions against the alternative of overdispersion and/or underdispersion.For more details see ?dispersiontest.2.ErrataThe following errors have been found in the book so far.Please report any further errors youfind to us.p.˜85–86:Due to a bug in the summary()method for“plm”objects,the degrees of freedom reported for the F˜statistics were interchanged and thus the p˜values were not correct.Therefore,the p˜values printed in the book at the end of summary(gr_fe)and summary(gr_re)are not correct,they should both be<ing plm1.1-1or higher,the code produces the correct output.p.˜92:Exercise˜6cannot be solved using PSID1982since that data set only containsa cross-section while Hausman-Taylor requires panel data.A panel version has beenavailable in the plm package under the name Wages;we have now added PSID7682 to AER for completeness(and consistent naming conventions).Use PSID7682for the exercise.p.˜169:The comment regarding the output from the Johansen test is in error.The null hypothesis of no cointegration is not rejected at the10%level.Nonetheless,the table corresponding to Case˜2in Juselius(2006,p.420)reveals that the trace statistic is significant at the15%level,thus the Johansen test weakly confirms the initial two-step approach.p.˜179:For consistency,the GARCH code should be preceded by data("MarkPound").p.˜205:The reference for Henningsen(2008)should be:Henningsen A(2008).“Demand Analysis with the Almost Ideal Demand Sys-tem in R:Package micEcon,”Unpublished.URL˜http://CRAN.R-project.org/package=micEcon.4AER:Package Vignette and ErrataNote:Currently,all links on manual pages corresponding to data sets taken from the Jour-nal of Business&Economic Statistics(JBES)archive are broken(data sets MarkPound,and RecreationDemand).The reason is the redesign of the American Statistical Association(ASA) website,rendering the old ASA data archive nonfunctional.The ASA journals manager cur-rently appears to supply data on a case-by-case basis.The problem awaits a more permanent solution.ReferencesBaltagi BH(2002).Econometrics.3rd edition.Springer-Verlag,New York.URL http:// /sgw/cda/frontpage/0,10735,4-165-2-107420-0,00.html.Cameron AC,Trivedi PK(1998).Regression Analysis of Count Data.Cambridge University Press,Cambridge.Davidson R,MacKinnon JG(2004).Econometric Theory and Methods.Oxford University Press,Oxford.Franses PH(1998).Time Series Models for Business and Economic Forecasting.Cambridge University Press,Cambridge.URL http://www.few.eur.nl/few/people/franses/ research/book2.htm.Greene WH(2003).Econometric Analysis.5th edition.Prentice Hall,Upper Saddle River, NJ.URL /~wgreene/Text/econometricanalysis.htm. Juselius K(2006).The Cointegrated VAR Model.Oxford University Press,Oxford.Kleiber C,Zeileis A(2008).Applied Econometrics with R.Springer-Verlag,New York.ISBN 978-0-387-77316-2.Kleiber C,Zeileis A(2009).AER:Applied Econometrics with R.R˜package version˜1.1-1, URL /package=AER.R Development Core Team(2008).R:A Language and Environment for Statistical Computing. R Foundation for Statistical Computing,Vienna,Austria.ISBN3-900051-07-0,URL http: ///.Stock JH,Watson MW(2007).Introduction to Econometrics.2nd edition.Addison-Wesley, Reading,MA.Verbeek M(2004).A Guide to Modern Econometrics.2nd edition.John Wiley&Sons, Hoboken,NJ.Christian Kleiber,Achim Zeileis5Affiliation:Christian KleiberWirtschaftswissenschaftliches Zentrum(WWZ)Universit¨a t BaselPeter Merian-Weg6CH-4002Basel,SwitzerlandE-mail:Christian.Kleiber@unibas.chURL:http://www.wwz.unibas.ch/kleiber/Achim ZeileisDepartment of Statistics and MathematicsWirtschaftsuniversit¨a t WienAugasse2–6AT-1090Wien,AustriaE-mail:Achim.Zeileis@URL:http://statmath.wu-wien.ac.at/~zeileis/。
Ryacas0包的说明信息说明书
Package‘Ryacas0’January12,2023Version0.4.4Title Legacy'Ryacas'(Interface to'Yacas'Computer Algebra System)Maintainer Mikkel Meyer Andersen<*************.dk>Encoding UTF-8Description A legacy version of'Ryacas',an interface to the'yacas'computer algebra system(<http: ///>).Depends R(>=3.3.0)Imports methods,Rcpp(>=0.12.0),stats,settings,xml2LinkingTo RcppSuggests devtools,exams,knitr,Matrix,pkgload,rmarkdown,igraph,testthatLicense GPL-2URL https:///r-cas/ryacas0,BugReports https:///r-cas/ryacas0/issuesRoxygenNote7.2.3VignetteBuilder knitrNeedsCompilation yesAuthor Mikkel Meyer Andersen[aut,cre,cph],Rob Goedman[aut,cph],Gabor Grothendieck[aut,cph],Søren Højsgaard[aut,cph],Grzegorz Mazur[aut,cph],Ayal Pinkus[aut,cph],Nemanja Trifunovic[cph](UTF-8part of yacas(src/yacas/include/yacas/utf8*))Repository CRANDate/Publication2023-01-1209:50:05UTC12Ryacas0-package R topics documented:Ryacas0-package (2)as.Sym.character (3)as.Sym.matrix (4)bodyAsExpression (4)Eval (5)getSyms (6)get_output_width (6)root (7)Ryacas_options (7)set_output_width (8)stripvar (8)syacas (9)Sym (9)yacas (10)yacasTranslations (14)yacas_evaluate (15)yacmode (16)y_ls (17)Index18 Ryacas0-package R interface to yacas computer algebra packageDescriptionRyacas0allows one to use the yacas computer algebra package entirely from within R.It takes an R expression,an R one line function or a yacas string and returns an R expression or a variety of other formats.It can be used for symbolic mathematics,exact arithmetic,ASCII pretty printing and R to TeX conversions.The main command is yacas and?yacas provides some information on installation and startup.DetailsThe following are sources of information on"Ryacas0":DESCRIPTIONfile library(help=Ryacas0)List of demofiles demo(package="Ryacas0")Demofile demo("Ryacas0")Demo demo("Ryacas0-PrettyPrinter")Demo demo("Ryacas0-Function")Demo demo("Ryacas0-Sym")Demo demo("Ryacas0-Expr")List Vignettes vignette(package="Ryacas0")Vignette vignette("Ryacas0")This File package?Ryacas0as.Sym.character3 Helpfiles?yacas,?yacasTranslations,?yacmode,?SymHelpfiles-Windows?yacasInstallNews RShowDoc("NEWS",package="Ryacas0")Acknowledgements RShowDoc("THANKS",package="Ryacas0")Wish List RShowDoc("WISHLIST",package="Ryacas0")Home page https:///r-cas/ryacas0/NoteThere is a note in the helpfile of the yacas command that discusses a number of installation and startup issues.Examplesprint(yacas(expression(integrate(1/x,x))))print(yacas("Integrate(x)1/x"))x<-Sym("x");Integrate(1/x,x)acos(Sym("1/2"))as.Sym.character Convert character vector to yacas objectDescriptionSimple and raw conversion to yacasUsage##S3method for class characteras.Sym(x,...)Argumentsx An R character vector....Not usedExamplesx<-c("a","2","4","c","d","6")xy<-as.Sym(x)yEval(y,list(a=3,c=3,d=3))4bodyAsExpression as.Sym.matrix Convert character matrix to yacas objectDescriptionSimple and raw conversion to yacasUsage##S3method for class matrixas.Sym(x,...)Argumentsx An R character matrix....Not usedExamplesx<-matrix(c("a","2","4","c","d","6"),3,2)xy<-as.Sym(x)yEval(y,list(a=3,c=3,d=3))bodyAsExpression Get body of function as an expression.DescriptionGet body of function as an expression.UsagebodyAsExpression(x)Argumentsx An R function.DetailsThis function is similar to the R body function except that function returns a call object whereas this one returns an expression usable in Ryacas calculations.Eval5 ValueAn expression.See AlsobodyExamples#construct an R function for the Burr probability density#function(PDF)given the Burr cumulative distribution function(CDF)BurrCDF<-function(x,c=1,k=1)1-(1+x^c)^-k#transfer CDF to yacasyacas(BurrCDF)#create a template for the PDF from the CDFBurrPDF<-BurrCDF#differentiate CDF and place resulting expression in bodybody(BurrPDF)<-yacas(expression(deriv(BurrCDF(x,c,k))))[[1]]#test out PDFBurrPDF(1)Eval Evaluate a yacas expression.DescriptionEvaluate a yacas expression.UsageEval(x,env=parent.frame(),...)Argumentsx Object to be evaluated.env Environment or list in which to perform evaluation....Not currently used.6get_output_widthExamplesEval(yacas(expression(x*x)),list(x=2))#samex<-2Eval(yacas(expression(x*x)))getSyms List Sym()objectsDescriptionLists all Sym()objects in the global environment(.GlobalEnv)UsagegetSyms(s=FALSE)Argumentss a logical value.If TRUE,all object names are returned.If FALSE,names which begin with a.are omitted.ExamplesgetSyms()xs<-Sym("x")getSyms()get_output_width Get width of yacas outputDescriptionGet width of yacas outputUsageget_output_width()root7 root Root functionDescriptionThe$y$’th root of$x$,i.e.$x^(1/y)$.Usageroot(x,y)Argumentsx Number to take$y$’th root ofy RootValueThe root y’th root of xRyacas_options Set or get options for the Ryacas packageDescriptionSet or get options for the Ryacas packageUsageRyacas_options(...)Arguments...Option names to retrieve option values or[key]=[value]pairs to set options. Supported optionsThe following options are supported•module_matvec_enabled(default TRUE):Print yacas List()’s as vectors and List(List(), ...)’s as matrices.•prettyform_default(default FALSE):Print yacas as PrettyForm()as default.8stripvar set_output_width Set width of yacas outputDescriptionSet width of yacas outputUsageset_output_width(w)Argumentsw Width in number of charactersstripvar Removes part of expression containing variableDescriptionYacas’Solve(eq,x)can return e.g.x==expr and{x==expr1,x==expr2,...}.Some usages are easier if the initial x==part is removed.This is the purpose of this function.Usagestripvar(expr,var)Argumentsexpr Expression where x==expr should be replaced to exprvar Name of variable,e.g.xValueExpression with left-hand side removedsyacas9 syacas yacas interface–silent versionDescriptionSimilar to yacas()but silent.This can be useful when working with yacas directly.Usagesyacas(x,...)Argumentsx A yacas character string or an R expression without terminating semicolon to be processed by yacas....Additional arguments ultimately passed down to yacas.character.See AlsoyacasSym SymDescriptionThe Symbol interface to yacas.UsageSym(...)Expr(x)Arguments...An R character string or object that can be coerced to a character string.x An R expression.10yacas DetailsAn object of class"Sym"is internally a yacas character string.An object of class"Expr"is in-ternally an R expression.One can combine such objects using the Math and Ops R operators (see help(Math)and help(Ops)for a list).Also there are methods for a number of R gener-ics:as.character.Sym,as.expression.Sym,determinant.Sym,deriv.Sym and print.Sym and yacas-oriented functions:Clear,Conjugate,Expand,Factor,Factorial,I,Identity,Infinity,Integrate, Inverse,InverseTaylor,Limit,List,N,Newton,Pi,Precision,PrettyForm,PrettyPrinter,Set,Sim-plify,Solve,Subst,Taylor,TeXForm,Transpose,Ver and"%Where%"all of which have the same meaning as the corresponding yacas commands.Try vignette("Rycas-Sym")for many examples.Get Sym objects with getSyms().ValueSym returns a"Sym"object and Expr returns an"Expr"object.NoteCurrently the only Expr methods implemented are as.character.Expr,deriv.Expr,Math.Expr,Ops.Expr and print.Expr.See Alsoas.Sym.matrix()Examplesx<-Sym("x")x*xIntegrate(x*x,x)Sym("%")%Where%list(x=10)acos(Sym("1/2"))y<-Exprq(x)y*yderiv(y*y,y)Exprq(acos(1/2))yacas yacas interfaceDescriptionInterface to the yacas computer algebra system.Usageyacas(x,...)##S3method for class characteryacas(x,verbose=FALSE,method,retclass=c("expression","character","unquote"),addSemi=TRUE,...)Argumentsx A yacas character string or an R expression without terminating semicolon to be processed by yacas....Additional arguments ultimately passed down to yacas.character.verbose A logical value indicating verbosity of output or"input"to only show input to yacas but not output from yacas or"output"to only show output from yacasbut not input to yacas.method method used to communicate with yacas.If"socket"is specified then the same yacas session is used on a sequence of calls.If"system"is specifiedthen a new instance of yacas is used just for the period of that call."system"does not require that the system be configured to support telnet/sockets and somay be useful in some instances.If no value is specified the default is takenfrom getOption("yacas.method")and if that is not specified"socket"is used."socket"and"system"may be abbreviated.addSemi If TRUE a semicolon is added to the character string sent to yacas.This can be set to FALSE if its known that the character string already has a trailing semicolon.It is ignored if retclass="expression".retclass The class of thefirst component of the yacas structure.It defaults to"expression"but may be specified as"character"or"unquote"."unquote"is the same as"character"except that if the character string returned would have otherwisehad quotes in thefirst and and last positions then they are stripped.DetailsThe user supplies an R expression,an R function name corresponding to a function with a single line body,a formula or a yacas input string.In the case of a formula it is regarded as an expression represented by the right hand side of the formula while the left hand side,if any,is ignored.Note the silent version syacas().ValueAn R object of class"yacas"is returned.If PrettyPrinter("OMForm")is in effect,which it is by default,then thefirst component is an R expression and the OMForm component contains Open-Math XML code.In other cases thefirst component is NULL and the YacasForm or PrettyForm components have display information.Generally an expression.Refer to details.NoteWindows Installation.On Windows one can install Ryacas by issuing the commands:install.packages("Ryacas",dep=TRUE)library(Ryacas)yacasInstall()or by using the Packages|Install package(s)menu in place of thefirst command.The sec-ond command downloads scripts.dat and yacas.exe from the internet and installs them into R_HOME/library/Ryacas/yacdir where R_HOME is the location of your R installation.Normally the default locations of yacas,its initializationfile and the scriptsfile are sufficient but, if necessary,they can be overridden via the environment variables:YACAS_HOME,YACAS_INIT and YACAS_SCRIPTS.The YACAS_INVOKE_STRING environment variable discussed in the next section overrides all three of these.All OS Installation.The YACAS_INVOKE_STRING environment variable can be used to override the invocation string for yacas.Normally it is not used.If it does need to be used then a typical use might be:library(Ryacas)#only need to do the file.copy command oncefile.copy(system.file("yacdir/R.ys",package="Ryacas"),"~/.yacsrc")#this needs to be done once per sessionSys.setenv(YACAS_INVOKE_STRING="yacas-pc--server9734")demo(Ryacas)#test it outyacmode.There is also a utility yacmode which is called without arguments and just turns R into a terminal into yacas until one quits out of it(and back to R)by entering stop,end,quit,exit or e.Startup.yacas starts up when yacasStart()is called or thefirst time yacas is called.yacas is shut down when yacasStop()is called or when the package is detached using the detach()R command.On Windows,when yacas is shut down,the yacas process is terminated on Windows XP Pro but not on other versions of Windows.In those cases there will be a dangling process that the user must terminate manually.Translation.The translation process occurs in several steps.If the input to the yacas function is an expression then it is translated to a valid yacas character string(otherwise,it is sent to yacas unprocessed).Yacas then processes the string and if retclass="expression"it is translated back to an R expression(otherwise it is sent back unprocessed).Examples of translations are:R yacassin(x)Sin(x)deriv(sin,x)Deriv(x)Sin(x)log(x)Ln(x)References/14yacasTranslations Examplesyacas(expression(Factor(x^2-1)))exp1<-expression(x^2+2*x^2)exp2<-expression(2*exp0)exp3<-expression(6*pi*x)exp4<-expression((exp1*(1-sin(exp3)))/exp2)print(yacas(exp4))print(yacas("Version()"))#yacas version#see demo("Ryacas-Function")yacasTranslations Yacas translationsDescriptionTranslations from R to the yacas computer algebra system.NoteThe translation process occurs in several steps.If the input to the yacas function is an expression then it is translated to a valid yacas character string(otherwise,it is sent to yacas unprocessed).Ya-cas then processes the string and if retclass="expression"it is translated back to an R expression (otherwise it is sent back unprocessed).Currently supported translations are:CONSTANTSR yacas======pi PiOPERATORSR yacas======7\%\%3Mod(7,3)7\%\/\%3Div(7,3)FUNCTIONSR yacas======sin(x)Sin(x)cos(x)Cos(x)yacas_evaluate15tan(x)Tan(x)asin(x)ArcSin(x)acos(x)ArcCos(x)atan(x)ArcTan(x)exp(x)Exp(x)sqrt(x)Sqrt(x)log(x)Ln(x)choose(n,k)Bin(n,k)gamma(x)Gamma(x)deriv(sin,x)Deriv(x)Sin(x)integrate(f,a,b)Integrate(x,a,b)f(x)list()List()factorial(n)n!Note the Limit example in demo(Ryacas0)for adding translations on thefly.The complete table under development.Author(s)Rob J GoedmanReferences/yacas_evaluate Evaluate yacas expressionDescriptionThis is a low-level function for evaluating yacas expression represented as string.Usageyacas_evaluate(expr)Argumentsexpr Yacas expressionValueResult of evaluating expr by yacas in OpenMath format and side-effects of the evaluationExamplesyacas_evaluate("D(x)Sin(x^2)")16yacmode yacmode yacmode interfaceDescriptionInteractive interface to the yacasUsageyacmode(enable_history=TRUE)Argumentsenable_history Use R history such that previous yacas commands can be used.Default is TRUE. DetailsThe user types valid yacas input and presses return.Type’quit’to return to R prompt.ValueOutput of yacas is returned.invisible NULLNoteNote that command will use R history()and modify it by default.Yacas is given a limited amount of time to complete,otherwise\[1\]CommandLine(1):User interrupted calculation is returned.E.g.Taylor(x,0,5)1/(1+x)will work,but Taylor(x,0,12)1/(1+x)is likely to take too long. References/Examples##Not run:yacmode()(x+y)^3-(x-y)^3Simplify(%)q##End(Not run)y_ls17 y_ls Get Yacas variablesDescriptionGet Yacas variablesUsagey_ls()ValueVector of variables defined in yacasIndex∗programmingRyacas0-package,2∗symbolmathbodyAsExpression,4Eval,5stripvar,8Sym,9yacas,10yacasTranslations,14yacmode,16%Where%(Sym),9addSemi(yacas),10as.character.Expr(Sym),9as.character.Sym(Sym),9as.character.yacas(yacas),10 as.Expr.formula(Sym),9as.expression.Sym(Sym),9as.expression.yacas(yacas),10 nguage(bodyAsExpression),4 as.Sym(Sym),9as.Sym.character,3as.Sym.matrix,4as.Sym.matrix(),10body,5 bodyAsExpression,4 CharacteristicEquation(Sym),9 Clear(Sym),9Conjugate(Sym),9deriv.Expr(Sym),9deriv.Sym(Sym),9 determinant.Expr(Sym),9 determinant.Sym(Sym),9 EigenValues(Sym),9Eval,5Expand(Sym),9Expr(Sym),9Exprq(Sym),9Factor(Sym),9Factorial(Sym),9FindRoots(Sym),9get_output_width,6getSyms,6I(Sym),9Identity(Sym),9Infinity(Sym),9Integrate(Sym),9Inverse(Sym),9InverseTaylor(Sym),9Limit(Sym),9List(Sym),9Math.Expr(Sym),9Math.Sym(Sym),9N(Sym),9Newton(Sym),9OpenMath2R(Sym),9Ops.Expr(Sym),9Ops.Sym(Sym),9Ops.yacas.symbol(Sym),9Pi(Sym),9Precision(Sym),9PrettyForm(Sym),9PrettyPrinter(Sym),9print.Expr(Sym),9print.Sym(Sym),9print.yacas(Sym),9root,7Ryacas0-package,2Ryacas_options,718INDEX19 Set(Sym),9set_output_width,8Simplify(Sym),9Solve(Sym),9stripvar,8Subst(Sym),9syacas,9syacas(),11Sym,9SymExpr(Sym),9Taylor(Sym),9TeXForm(Sym),9trans(Sym),9Transpose(Sym),9transtab(Sym),9Ver(Sym),9y_ls,17yacas,3,10yacas(),9yacas.symbol.value(Sym),9yacas_evaluate,15yacasTranslations,14yacmode,16yAssignFunction(yacas),10yDeriv(Sym),9yFactorial(Sym),9yIntegrate(Sym),9yLimit(Sym),9ynext(yacas),10yparse(yacas),10yrewrite(Sym),9ySequence(yacas),10ysub(yacas),10yUnlist(Sym),9。
mxGraph官方文档及其翻译整理
翻译外文原文1 OverviewThe mxGraph package contains a client software, written in JavaScript, and a series of backends for various languages. The client software is a graph component with an optional application wrapper that is integrated into an existing web interface. The client requires a webserver to deliver the required files to the client or can be run from the local filesystem without a webserver. The backends may be used as is, or they may be embedded into an existing server application in one of the supported languages.If a backend exists, then the client may be configured to use this backend in various ways, such as: Creating imagesStoring and loading diagramsCreating an object representation of a graphSharing diagrams with other clientsThe above scenarios maybe combined in various ways, such as sending an XML description of each change to the backend as it happens, or autosaving of the diagram to avoid loss of data on the client. The client can also operate in offline mode, where it does not require a backend or a webserver.Please have a look at the index files in the respective directories for information on the various backends. Java.NETPHP2 Hello, World!The Hello, World! example of mxGraph ships in a single HTML file, which contains the required namespaces, the mxGraph library script and the example code. The example can be viewed by pointing Firefoxor Internet Explorer to the link above either on the local filesystem or on a webserver. To display the source of the example press Control-U in Firefox or click Page, V iew Source in Internet Explorer.2.1 LibraryThe HEAD part of the page contains the JavaScript code and dependencies. The library is loaded using the following code. The mxBasePath variable is used to define the path where the library loads its resources from. This variable must be defined prior to loading the library code and should not include a trailing slash.<script type="text/javascript">mxBasePath = 'javascript/src';</script><script type="text/javascript" src="javascript/src/js/mxClient.js"></script>mxClient.js contains all required code in a single file. Note that the source code only ships with the commercial distributions. In the evaluation version, the source code is loaded from a server using a special URL. Y ou should not make local copies of the evaluation source code.2.2 Browser CheckThe next script tag in the HEAD part of the page contains the Hello, World! example code. The first part of the code checks if the browser that is displaying the page is supported by the library. It is recommended to do this as the first step of the program and display an error message if the browser is not supported. In your document you may also want to include a NOSCRIPT directive for browsers that have JavaScript disabled, however, in our examples this directive is not used.There is no convention for the name of the main function. The function is invoked from the onload handler in the page and may have any name and arguments. In this case, the argument is a DOM node that will contain the graph. Note that the DOM node may have any ID and that the code is independent of this ID.<script type="text/javascript";>function main(container){// Checks if the browser is supportedif (!mxClient.isBrowserSupported()){// Displays an error message if the browser is not supported.mxUtils.error('Browser is not supported!', 200, false);}...2.3 ContainerFor the JavaScript to actually render the graph, the page contains an DOM node which will display the graph. This DOM node is either dynamically created or it is obtained via an ID usingdocument.getElementById as in the Hello, World! example. The DOM node is passed to the main function and is used to construct the graph instance as shown below.If you want the container to have scrollbars, use the overflow:auto CSS directive instead of overflow:hidden in the style of the container.2.4 GraphThe code constructs an empty graph model and passes the container and the empty model to the graph constructor. For this example, all default event handling is disabled in the last line.var model = new mxGraphModel();var graph = new mxGraph(container, model);If you want the graph to be read-only you can use graph.setEnabled(false).2.5 V ertices and EdgesTo insert vertices and edges, beginUpdate and endUpdate are used to create a transaction. The endUpdate should always go into a finally-block to make sure it is always executed if the beginUpdatewas executed. However, the beginUpdate should not be part of the try-block to make sure endUpdate is never executed if beginUpdate fails. This is required for the model to remain in a consistent state, that is, for each call to beginUpdate there should always be exactly one call to endUpdate.The part within the try-block creates the vertices and edges for the graph. The default parent is obtained from the graph and is typically the first child of the root cell in the model, which is created automatically when using the graph model c'tor with no arguments.// Gets the default parent for inserting new cells. This// is normally the first child of the root (ie. layer 0).var parent = graph.getDefaultParent();// Adds cells to the model in a single stepmodel.beginUpdate();try{var v1 = graph.insertV ertex(parent, null, 'Hello,', 20, 20, 80, 30);var v2 = graph.insertV ertex(parent, null, 'World!', 200, 150, 80, 30);var e1 = graph.insertEdge(parent, null, '', v1, v2);}finally{// Updates the displaymodel.endUpdate();}The use of beginUpdate and endUpdate does not only improve the display performance, but it is also used to mark the boundaries for undoable changes when undo/redo is used.3 GraphsInstantiate mxGraph in order to create a graph. This is the central class in the API. Everything else is auxiliary.To create a new graph instance, a DOM node (typically a DIV) is required:var node = document.getElementById('id-of-graph-container');var graph = new mxGraph(node);3.1 ModelmxCell defines the elements of the graph model, which is implemented by mxGraphModel.The graph model has the following properties:The root element of the graph contains the layers. The parent of each layer is the root element.A layer may contain elements of the graph model, namely vertices, edges and groups.Groups may contain elements of the graph model, recursively.The graph and structural information is stored in the cells, as well as the user objects, which are used to store the value associated with the cells (aka business objects).To create a new graph model with a root cell and a default layer (first child):var root = new mxCell();root.insert(new mxCell());var model = new mxGraphModel(root);3.2 StylesheetThe appearance of the cells in a graph is defined by the stylesheet, which is an instance of mxStylesheet. The stylesheet maps from stylenames to styles. A style is an array of key, value pairs to be used with the cells. The keys are defined in mxConstants and the values may be strings and numbers or JavaScript objects or functions.To modify the default styles for vertices and edges in an existing graph:var vertexStyle = graph.getStylesheet().getDefaultV ertexStyle();vertexStyle[mxConstants.ROUNDED] = true;var edgeStyle = graph.getStylesheet().getDefaultEdgeStyle();edgeStyle[mxConstants.STYLE_EDGE] = mxEdgeStyle.TopToBottom;3.3 StylesThe style information for a cell is stored in cell.style. The style is part of the cell's state and is normally changed via mxGraphModel.setStyle, which will update all views. The cell style is a string of the form [stylename;|key=value;]which tells the graph to use the given named styles and override the specified key, value pairs in the given order. For example, to use the rounded style and override the stroke- and fillColor, the style would be defined as:rounded;strokeColor=red;fillColor=greenTo use the above in Hello, World!, the stylename would be passed to the insertV ertex method as follows: var v1 = graph.insertV ertex(parent, null, 'Hello',20, 20, 80, 30, 'rounded;strokeColor=red;fillColor=green');3.4 AppearanceIn certain cases you may want to override specific attributes based on dynamic properties of a cell (ie. it's value, aka. userobject), such as the image, indicator shape, -image, -color or -gradient color), in which case you can override getImage, getIndicatorShape, getIndicatorImage, getIndicatorColor and getIndicatorGradientColor res pectively. Note that these methods take a cell state as an argument, which points to a "resolved" (that is, an array) version of the cell's style. Hence, the default implementation for getImage looks as follows: mxGraph.prototype.getImage = function(state){if (state != null && state.style != null){return state.style[mxConstants.STYLE_IMAGE];}return null;}This method may be overridden to return any image for the given state. Typically, the image is defined by either state.cell, which points to the graph cell associated with the state, or bystate.cell.value, which refers to the cell's user object.Due to the nature of the display, where all cells are created once and updated only if the model fires a notification for a change, you must invoke view.invalidate(cell) for each cell who's image has changed, and call view.validate to update the display.4 EditorsInstantiate mxEditor in order to create an editor. This is the central class in the editor package. Everything else in this package is auxiliary. To create a new editor instance and configure it using a config file, you can pass the name of the config file to the mxEditor constructor.To create a new editor instance and configure it, the following code is used:var config = mxUtils.load('editors/config/keyhandler-commons.xml').getDocumentElement();var editor = new mxEditor(config);The configuration file is an XML file that is passed to mxCodec, which in turn uses mxEditorCodec and others to read the XML into the editor object hierarchy. This is normally done at startup time to configure the editor, graph, model, toolbar, popupmenus etc using the I/O subsystem.4.1 CSSThe CSS stylesheet contains the style definitions for various elements of the user interface, such as the rubberband selection, the in-place editor or the popup menu. It also contains the directives required to enable VML support in Internet Explorer, so it is substantial that the stylesheet is included in the page.Additional stylesheets may either be added programmatically using mxClient.link('stylesheet', filename) or via a stylesheet tag of the UI section in the editor configuration, eg.:<mxEditor><ui><stylesheet name="examples/editors/css/process.css"/>...4.2 TemplatesTo add new cell types, create a template in the templates array section of the model in the config file (mxEditor/mxGraph/mxGraphModel/Array[as=templates]) as follows:<add as="symbol"><Symbol label="Symbol" customAttribute="whatever"><mxCell vertex="1" connectable="1" style="symbol;image=images/event.png"><mxGeometry as="geometry" width="32" height="32"/></mxCell><CustomChild customAttribute="whatever"/></Symbol></add>The as-attribute of the add-element contains the name under which the template will be accessible for later use. The Symbol-child element is a custom (ie workflow) element, and can have any name and any number of child elements and custom attributes. The label attribute is a special one that is used for the textual representation of the cell in the graph. The mxCell element is another special child node which contains the graphical information for the cell, namely, the cell-type, -style, -size and -position.See mxGraph.convertV alueToString if you would like to use another attribute or a combination of attributes for the textual representation, and mxCell.valueChanged to handle in-place editing by storing the new text value in the respective attribute(s).4.3 ToolbarTo use the template in the graph, a toolbar item must be added which refers to the template in the mxDefaultToolbar section of the config file (mxEditor/mxDefaultToolbar[as=toolbar]) as follows:<add as="symbolTool" template="symbol"style="symbol;image=wf/images/bpmn/special_event.png"icon="wf/images/bpmn/small_event.gif"/>The as attribute specifies the tooltip to be displayed for the icon in the toolbar, the template-attribute refers to the name under which the template was previously added. The style- attribute is optional, and may be used to override the style defined in the template definition. Finally, the icon specifies the icon to be used for thetoolbar item.Note that the as attribute is assumed to be the key for a language resource, in this case symbolTool. If the resource is not defined in mxResources, then the attribute value is used as the label.5 Input/OutputThe default encoding scheme maps all non-object fields to string attributes and all object fields to child nodes, using the constructor name of the object as the nodename and the fieldname for the as-attribute value. This default encoding scheme may be overridden by custom codecs, which are registered in the mxCodecRegistry.For example, consider the following JavaScript object definition:var object = new Object();object.myBool = true;object.myObject = new Object(); = 'Test';object.myArray = ['a', ['b', 'c'], 'd'];To encode this object and show the resulting XML in a new window, the following code is used:var encoder = new mxCodec();var node = encoder.encode(object);mxUtils.popup(mxUtils.getXml(node));And here is the XML structure that represents the object:<Object myBool="1"><Object name="Test" as="myObject"/><Array as="myArray"><add value="a"/><Array><add value="b"/><add value="c"/></Array><add value="d"/></Array></Object>Note that the codecs will turn booleans into numeric values, no array indices are stored if they are numeric and non-object array members are stored inside the value-attribute. Furthermore one may include other XML files by use of the include directive in the XML structures.5.1 FilesThe save, open, readGraphModel and writeGraphModel functions implement a standard mechanism for handling files in mxEditor.The default implementation of mxEditor.save is called with an argument to indicate if the save was triggered by the user or by the system. It then uses the urlPost variable of the editor object to check if a post request should be issued. If the variable is defined, the editor issues a post request to the specified URL passing the XML along as a POST variable called xml.5.2 PostAs an example, consider the following PHP file which is located in the same directory as the HTML page. If the filename is server.php then the urlPost variable must be set to server.php on the editor in order to post the diagram to the server. The PHP file will get the XML from the POSt request and write it to a file called diagram.xml.<?php$xml = $HTTP_POST_V ARS['xml'];if ($xml != null) {$fh=fopen("diagram.xml","w");fputs($fh, stripslashes($xml));fclose($fh);}>To set the URL to post to, change the respective entry in the mxEditor node of the config file as follows:<mxEditor urlPost="/server.php" ... >Keep in mind that the JavaScript can only post to the server where it originated from, so we recommend to use relative URLs, eg. server.php.5.3 Form FieldsIf you need to read/write the graph from/to a string (eg. to fill a form-field), you can use the following methods:var data = editor.writeGraphModel();editor.readGraphModel(mxUtils.parseXml(data));5.4 CodecsFor encoding other objects, or if no editor instance is available, the mxCodec can be used to create and read XML data.中文译文1. Overview 概述该mxGraph包包含一个用JavaScript编写的客户端,以及一系列各种后端语言编写的功能文件。
type-aliases-package写法 -回复
type-aliases-package写法-回复什么是[typealiases package写法]?在编程中,[typealiases package写法]是一种技术,用于定义和使用类型别名。
类型别名是给现有类型创建一个新的名称,以便在代码中更方便地使用它。
使用[typealiases package写法]可以提高代码的可读性和可维护性,使其更易于理解和扩展。
在大多数编程语言中,类型别名可以通过关键字来创建,例如C++中的`typedef`、Java中的`alias`和Swift中的`typealias`。
与此类似,[typealiases package写法]也提供了一种定义和使用类型别名的方式,使程序员能够更灵活地处理各种类型。
[typealiases package写法]的使用方法如下所示:步骤1:导入[typealiases package]在代码的开头或需要使用类型别名的地方,必须先导入[typealiases package]。
导入[typealiases package]的语法因编程语言而异,但通常使用`import`关键字或类似的方式。
步骤2:定义类型别名使用[typealiases package]提供的语法,可以定义类型别名。
类型别名的语法因编程语言而异,但通常是将新的名称与现有的类型进行映射。
例如,在C++中,可以使用`using`关键字来定义类型别名:using NewTypeName = ExistingType;在Java中,可以使用`alias`关键字来定义类型别名:alias NewTypeName = ExistingType;在Swift中,可以使用`typealias`关键字来定义类型别名:typealias NewTypeName = ExistingType步骤3:使用类型别名一旦类型别名被定义,就可以在代码的其他部分使用它。
根据具体的编程语言和需求,可以将类型别名用于变量声明、函数参数、返回类型等场景。
go语言中var声明chan、map、指针,注意的情况
go语⾔中var声明chan、map、指针,注意的情况在处理超时时候出现的问题:问题代码为package mainimport( "fmt" "time")func main(){var ch chan stringgo func() {ch <- "result"}()select {case res := <-ch:fmt.Println(res)returncase <-time.After(time.Second * 5):fmt.Println("timeout")}} 错误的原因:var ch chan string没有对ch分配空间,使得⼀直运⾏的是case <- time.After(time.Second*5)这个分⽀。
解决⽅法为添加:ch = make(chan string)或者删除var ch chan string,再添加ch := make(chan string)思考: var在声明指针、chan、map的时候都要使⽤make分配⼀下空间,否则⽆法使⽤实现map的⽐较:var kl map[string]stringkl["string"]="stk"fmt.Println(kl) //出现错误var kt map[string]stringkt = make(map[string]string)kt["string"] = "strin"fmt.Println(kt) //正确。
mappers标签引入映射器的四种方式
mappers标签引⼊映射器的四种⽅式<!-- Using classpath relative resources --><mappers><mapper resource="org/mybatis/builder/AuthorMapper.xml"/><mapper resource="org/mybatis/builder/BlogMapper.xml"/><mapper resource="org/mybatis/builder/PostMapper.xml"/></mappers><!-- Using url fully qualified paths --><mappers><mapper url="file:///var/mappers/AuthorMapper.xml"/><mapper url="file:///var/mappers/BlogMapper.xml"/><mapper url="file:///var/mappers/PostMapper.xml"/></mappers>第三种⽅式:mapper标签,通过class属性指定mapper接⼝名称,此时对应的映射⽂件必须与接⼝位于同⼀路径下,并且名称如mapper接⼝采⽤注解的⽅式,则⽆需映射⽂件windows系统下,映射⽂件不区分⼤⼩写,linux系统没有验证<!-- Using mapper interface classes --><mappers><mapper class="org.mybatis.builder.AuthorMapper"/><mapper class="org.mybatis.builder.BlogMapper"/><mapper class="org.mybatis.builder.PostMapper"/></mappers>第四种⽅式:package标签,通过name属性指定mapper接⼝所在的包名 ,此时对应的映射⽂件必须与接⼝位于同⼀路径下,并且如mapper接⼝采⽤注解的⽅式,则⽆需映射⽂件windows系统下,映射⽂件不区分⼤⼩写,linux系统没有验证<!-- Register all interfaces in a package as mappers --><mappers><package name="org.mybatis.builder"/></mappers>。
VAM包:变异调整马哈拉诺比距方法版本1.1.0说明书
Package‘V AM’November5,2023Type PackageTitle Variance-Adjusted MahalanobisVersion1.1.0Author H.Robert FrostMaintainer H.Robert Frost<***********************>Description Contains logic for cell-specific gene set scoring of single cell RNA sequencing data. Depends R(>=3.6.0),MASS,MatrixImports methods(>=3.6.0)Suggests Seurat(>=4.0.0),SeuratObject(>=4.0.0),sctransform(>=0.3.2)License GPL(>=2)Copyright Dartmouth CollegeEncoding UTF-8NeedsCompilation noRepository CRANDate/Publication2023-11-0516:30:02UTCR topics documented:V AM-package (2)createGeneSetCollection (2)vam (3)vamForCollection (5)vamForSeurat (6)Index812createGeneSetCollection VAM-package Variance-Adjusted MahalanobisDescriptionImplementation of Variance-adjusted Mahalanobis(V AM),a method for cell-specific gene set scor-ing of scRNA-seq data.DetailsPackage:V AMType:PackageVersion: 1.0.0Date:2021License:GPL-2NoteThis work was supported by the National Institutes of Health grants K01LM012426,R21CA253408, P20GM130454and P30CA023108.Author(s)H.Robert FrostReferences•Frost,H.R.(2020).Variance-adjusted Mahalanobis(V AM):a fast and accurate method forcell-specific gene set scoring.biorXiv e-prints.doi:https:///10.1101/2020.02.18.954321createGeneSetCollectionUtility function to help create gene set collection list objectDescriptionUtility function that creates a gene set collection list in the format required by vamForCollection() given the gene IDs measured in the expression matrix and a list of gene sets as defined by the IDs of the member genes.vam3UsagecreateGeneSetCollection(gene.ids,gene.set.collection,min.size=1,max.size) Argumentsgene.ids Vector of gene IDs.This should correspond to the genes measured in the gene expression data.gene.set.collectionList of gene sets where each element in the list corresponds to a gene set andthe list element is a vector of gene IDs.List names are gene set names.Mustcontain at least one gene set.min.size Minimum gene set size afterfiltering out genes not in the gene.ids vector.Gene sets whose post-filtering size is below this are removed from thefinal collectionlist.Default is1and cannot be set to less than1.max.size Maximum gene set size afterfiltering out genes not in the gene.ids vector.Gene sets whose post-filtering size is above this are removed from thefinal collectionlist.If not specified,nofiltering is performed.ValueVersion of the input gene.set.collection list where gene IDs have been replaced by position indices, genes not present in the gene.ids vector have been removed and gene sets failing the min/max size constraints have been removed.See AlsovamExamples#Create a collection with two sets defined over3genescreateGeneSetCollection(gene.ids=c("A","B","C"),gene.set.collection=list(set1=c("A","B"),set2=c("B","C")),min.size=2,max.size=3)vam Variance-adjusted Mahalanobis(VAM)algorithmDescriptionImplementation of the Variance-adjusted Mahalanobis(V AM)method,which computes distance statistics and one-sided p-values for all cells in the specified single cell gene expression matrix.This matrix should reflect the subset of the full expression profile that corresponds to a single gene set.The p-values will be computed using either a chi-square distribution,a non-central chi-square distribution or gamma distribution as controlled by the center and gamma arguments for the one-sided alternative hypothesis that the expression values in the cell are further from the mean (center=T)or origin(center=F)than expected under the null of uncorrelated technical noise,i.e., gene expression variance is purely technical and all genes are uncorrelated.4vamUsagevam(gene.expr,tech.var.prop,gene.weights,center=FALSE,gamma=TRUE)Argumentsgene.expr An n x p matrix of gene expression values for n cells and p genes.tech.var.prop Vector of technical variance proportions for each of the p genes.If specified, the Mahalanobis distance will be computed using a diagonal covariance matrixgenerated using these proportions.If not specified,the Mahalanobis distanceswill be computed using a diagonal covariance matrix generated from the samplevariances.gene.weights Optional vector of gene weights.If specified,weights must be>0.The weights are used to adjust the gene variance values included in the computation of themodified Mahalanobis distances.Specifically,the gene variance is divided bythe gene weight.This adjustment means that large weights will increase theinfluence of a given gene in the computation of the modified Mahalanobis dis-tance.center If true,will mean center the values in the computation of the Mahalanobis statis-tic.If false,will compute the Mahalanobis distance from the origin.Default isF.gamma If true,willfit a gamma distribution to the non-zero squared Mahalanobis dis-tances computed from a row-permuted version of gene.expr.The estimatedgamma distribution will be used to compute a one-sided p-value for each cell.Iffalse,will compute the p-value using the standard chi-square approximation forthe squared Mahalanobis distance(or non-central if center=F).Default is T. ValueA data.frame with the following elements(row names will match row names from gene.expr):•"cdf.value":1minus the one-sided p-values computed from the squared adjusted Mahalanobis distances.•"distance.sq":The squared adjusted Mahalanobis distances for the n cells.See AlsovamForCollection,vamForSeuratExamples#Simulate Poisson expression data for10genes and10cellsgene.expr=matrix(rpois(100,lambda=2),nrow=10)#Simulate technical variance proportionstech.var.prop=runif(10)#Execute VAM to compute scores for the10genes on each cellvam(gene.expr=gene.expr,tech.var.prop=tech.var.prop)#Create weights that prioritize the first5genesgene.weights=c(rep(2,5),rep(1,5))vamForCollection5 #Execute VAM using the weightsvam(gene.expr=gene.expr,tech.var.prop=tech.var.prop,gene.weights=gene.weights)vamForCollection VAM method for multiple gene setsDescriptionExecutes the Variance-adjusted Mahalanobis(V AM)method(vam)on multiple gene sets,i.e.,a gene set collection.UsagevamForCollection(gene.expr,gene.set.collection,tech.var.prop,gene.weights,center=FALSE,gamma=TRUE)Argumentsgene.expr An n x p matrix of gene expression values for n cells and p genes.gene.set.collectionList of m gene sets for which scores are computed.Each element in the list cor-responds to a gene set and the list element is a vector of indices for the genes inthe set.The index value is defined relative to the order of genes in the gene.exprmatrix.Gene set names should be specified as list names.tech.var.prop See description in vamgene.weights See description in vam.If specified as a single vector of weights,weights must be specified for all p genes and the same weights are used for all gene sets.Touse different weights for each set,specify as a list of the same length as thegene.set.collection list.In this case,each list element should be a vector ofgene weights of the same length as the size of the corresponding gene set.center See description in vamgamma See description in vamValueA list containing two elements:•"cdf.value":n x m matrix of1minus the one-sided p-values for the m gene sets and n cells.•"distance.sq":n x m matrix of squared adjusted Mahalanobis distances for the m gene sets and n cells.See Alsovam,vamForSeuratExamples#Simulate Poisson expression data for10genes and10cellsgene.expr=matrix(rpois(100,lambda=2),nrow=10)#Simulate technical variance proportionstech.var.prop=runif(10)#Define a collection with two disjoint sets that span the10genescollection=list(set1=1:5,set2=6:10)#Execute VAM on both sets using default values for center and gammavamForCollection(gene.expr=gene.expr,gene.set.collection=collection,tech.var.prop=tech.var.prop)#Create weights that prioritize the first2genes for the first set#and the last2genes for the second setgene.weights=list(c(2,2,1,1,1),c(1,1,1,2,2))#Execute VAM using the weightsvamForCollection(gene.expr=gene.expr,gene.set.collection=collection,tech.var.prop=tech.var.prop,gene.weights=gene.weights)vamForSeurat VAM wrapper for scRNA-seq data processed using the Seurat frame-workDescriptionExecutes the Variance-adjusted Mahalanobis(V AM)method(vamForCollection)on normalized scRNA-seq data stored in a Seurat object.If the Seurat NormalizeData method was used for normalization,the technical variance of each gene is computed as the proportion of technical variance(from FindVariableFeatures)multiplied by the variance of the normalized counts.If SCTransform was used for normalization,the technical variance for each gene is set to1(the nor-malized counts output by SCTransform should have variance1if there is only technical variation). UsagevamForSeurat(seurat.data,gene.weights,gene.set.collection,center=FALSE,gamma=TRUE,sample.cov=FALSE,return.dist=FALSE)Argumentsseurat.data The Seurat object that holds the scRNA-seq data.Assumes normalization has already been performed.gene.weights See description in vamForCollectiongene.set.collectionList of m gene sets for which scores are computed.Each element in the listcorresponds to a gene set and the list element is a vector of indices for the genesin the set.The index value is defined relative to the order of genes in the relevantseurat.data Assay object.Gene set names should be specified as list names.center See description in vamgamma See description in vamsample.cov If true,will use the a diagonal covariance matrix generated from the sample vari-ances to compute the squared adjusted Mahalanobis distances(this is equivalentto not specifying tech.var for the vam method).If false(default),will use thetechnical variances as determined based on the type of Seurat normalization.return.dist If true,will return the squared adjusted Mahalanobis distances in a new Assayobject called"V AM.dist".Default is F.ValueUpdated Seurat object that hold the V AM results in one or two new Assay objects:•If return.dist is true,the matrix of squared adjusted Mahalanobis distances will be storedin new Assay object called"V AM.dist".•The matrix of CDF values(1minus the one-sided p-values)will be stored in new Assay objectcalled"V AM.cdf".See Alsovam,vamForCollectionExamples#Only run example code if Seurat package is availableif(requireNamespace("Seurat",quietly=TRUE)&requireNamespace("SeuratObject",quietly=TRUE)){ #Define a collection with one gene set for the first10genescollection=list(set1=1:10)#Execute on the pbmc_small scRNA-seq data set included with SeuratObject#See vignettes for more detailed Seurat examplesvamForSeurat(seurat.data=SeuratObject::pbmc_small,gene.set.collection=collection)}Index∗filecreateGeneSetCollection,2vam,3vamForCollection,5vamForSeurat,6∗packageVAM-package,2 createGeneSetCollection,2vam,3,3,5–7VAM-package,2vamForCollection,4,5,6,7vamForSeurat,4,5,68。
qlsql学习笔记
、PL/SQL中的DML操作:1、select * [into v_var/v_record]from tb_name[where expression]2、insert into tb_namevalues()[returning rowid,tb_row into v_rowid,v_var]3、update tb_name(这里也可以是个select查询)set tb_col=expression[where expression/current of cur_name][returning rowid,tb_row into v_rowid,v_var](注意:没有from关键字,sqlserver中是有的p)4、deletefrom tb_name[where expression/current of cur_name][returning rowid,tb_row into v_rowid,v_var]二、语句块结构1、<<de_name>>declare/*declaretive section*/begin/*statment*/exception/*exception section*/end de_name三、错误处理1、申明异常declare e_val exception2、抛出异常raise e_val3、处理异常exception when e_val1 then expression1;when e_val2 then expression2;...;end;4、others异常处理器:能捕获所有的异常,有2个内置函数sqlcode,sqlerrmwhen others thenv_errorcode:=sqlcode;v_errortext:=substr(sqlerrm,1,200);insert into log_table values(v_errorcode,v_errortext);5、raise_application_error:创建自己的错误的消息四、变量1、v_var 类型[constant] [not null] [:=value]五、类型1、标量类型:char、number、date2、复合类型:record、nested table、index-by table、varray3、LOB类型:BFILE、LOB、CLOB、NLOB4、引用类型:REF CURSOR、REF OBJECT TYPE5、对象类型:object type、sys.anytype、sys.anydata、sys.anydateset六、条件语句1、if expression then/*statment*/elsif expression then/*statment*/else/*statment*/end if2、<<case_name>>case test_varwhen value1 then expression1;when value2 then expression2;when value3 then expression3;else expression;end case case_name;3、<<case_name>>casewhen expression1 then expression1;when expression2 then expression2;when expression3 then expression3;else expression;end case case_name;七、循环结构1、loop/*statment*/if expression then exit;end if;end loop2、loop/*statment*/exit when expression;end loop3、while expression loop/*statment*/end loop4、for v_count in [reverse] 1..10 loop/*statment*/end loop八、GOTO语句1、/*statment*/if expression then goto 1_name;/*statment*/<<1_nanme>>null;(空语句)九、动态sql语句1、execute immediate statment [into v_var] [using]例1:execute immediate 'select count(*) from emp' into v_count例2:execute immediate 'select * from emp where emp_id<=:v_id' using 7788一○、批绑定1、forall v_count in 1..10 (此处没有loop循环)/*dml_statment*/1)、事务性问题:操作中一行有错误,只有该行回滚,其他的提交(参考forall.sql)2)、有save exception特性(参考forall.sql)2、bulk collect:可以用于select into,fetch into,returning into一一、自治事务(它是独立的,与父事务状态无关)1、pragma autonomous_transaction2、必须在语句块的说明部分3、只有(顶层自治块;本地的、单个的和打包的子程序;对象类型的方法;数据库触发器)可以标记为自治4、申明为自治的事务必须要以commit或rollback语句结束一二、游标1、cursor cur_name(v_var1,v_var2..) is select_statment [for update of col_1,col_2..] [nowait/wait n];open cur_name;fetch cur_name into v_var;close cur_name;2、属性有:%found、%notfound、%isopen、%rowcount3、处理隐式游标:sql%notfound、sql5rowcount等等4、游标for循环:游标申明后即可用for v_count in cur_name loop...end loop处理数据5、隐式for循环:for v_count in (select * from tb_name) loop...end loop;6、游标变量声明:type type_name is ref cursor [return return_type]7、游标变量使用:open v_cursorvar for select ...一三、过程和函数1、create or replace procedure proc_name(var [in|out|in out] type,..)asbegin/*statment*/end2、create or replace function func_name(var [in|out|in out] type,..)return return_typeasbegin/*statment*/return expression;end3、call的用法:call proc/func/对象的方法/java子程序(argument_list)call func(argument_list) into host_variable(只限于函数)(注意:call是sql语句,不是pl/sql语句)一四、包1、创建包头:create or replace package package_nameas/*...*/end2、创建包体:create or replace package body body_nameas/*...*/end3、可串行复用的包:create or replace package package_name aspragma serially_reusable(申明为可串行复用)4、可串行复用的包的特点是重置包内的游标的状态,节省内存一五、使用共享池(dbms_shared_pool)1、keep(name,flag)锁定对象在共享池中2、unkeep(name,flag)删除共享池中的对象3、sizes(minsize number)把共享池中的内容响应到屏幕上4、aborted_request_threshold(size number)oracle不会释放对象,除非至少需要size个字节一六、触发器1、触发器格式:create or replace trigger trigger_name{before|after|instead of} {insert|update|delete}on object_namedeclare/*..*/begin/*statment*/end2、系统触发器:create or replace trigger trigger_name{before|after} {事件}on object_name[for each row]declare/*..*/begin/*statment*/end注意:after的事件:starup,servererror,logonbefore的事件:shutdown,logoff同时满足的:create,drop,alter3、限制:不能发出事务控制语句(如:commit,rollback等);其调用的proc和func里不能有事务控制语句(自治事务除外)4、变异表:触发器中对触发器的本身触发的表再有查询的动作,那就是变异表;(参考方案mutating.sql)一七、集合1、index-by表type t_val is table of type index by binary_integer2、嵌套表type t_val is table of type [not null](一定要初始化)3、可变数组type t_val is varray(int) of type [not null]4、exists,count,limit,5、first,last,next,prior6、extend,trim,delete一八、对象(参考point.sql,pointsql.sql)1、create or replace type obj_name as OBJECT(/*statment*/)2、create or replace type body obj_name as/*statment*/begin/*statment*/end;3、大对象(LOB)(参考lob_dml.sql)一九、管道化表函数(参考pipelined.sql)1、返回整个行的集的函数,不是一次全部返回2、作用:把数据从一种类型转化成另一种类型二○、表函数1、返回整个行的集(作为一个集合)的函数二一、外部里程1、C外部例程1)、先把你的C函数编译到操作系统上的一个共享库中;2)、建立监听程序来支持与外部例程驱动器extproc的连接;3)、创建一个数据字典对象来代表操作系统上的共享库;create or replace library sendmaillibraryas '/libs/libmail.so';4)、创建包装来调用该例程。
常见linux笔试题-100道选择题-(答案见最后)
Linux认证笔试基本题(答案见最后)(以下均为单选题)01.D 02.B 03.C 04.C 05.B 06.C 07.B 0 8.C 09.A 10.B1.cron 后台常驻程序 (daemon) 用于:A. 负责文件在网络中的共享B. 管理打印子系统C. 跟踪管理系统信息和错误D. 管理系统日常任务的调度2.在大多数Linux发行版本中,以下哪个属于块设备 (block devices) ?A. 串行口B. 硬盘C. 虚拟终端D. 打印机3.下面哪个Linux命令可以一次显示一页内容?A. pauseB. catC. moreD. grep4.怎样了解您在当前目录下还有多大空间?A. Use dfB. Use du /C. Use du .D. Use df .5.怎样更改一个文件的权限设置?A. attribB. chmodC. changeD. file6.假如您需要找出 /etc/my.conf 文件属于哪个包 (package) ,您可以执行:A. rpm -q /etc/my.confB. rpm -requires /etc/my.confC. rpm -qf /etc/my.confD. rpm -q | grep /etc/my.conf7.假如当前系统是在 level 3 运行,怎样不重启系统就可转换到 level 5 运行?A. Set level = 5B. telinit 5C. run 5D. ALT-F7-58.那个命令用于改变 IDE 硬盘的设置?A. hdparamB. ideconfigC. hdparmD. hddparm9.下面哪个命令可以列出定义在以后特定时间运行一次的所有任务?A. atqB. cronC. batchD. at10.下面命令的作用是:set PS1="[\u\w\t]\\$" ; export PS1A. 改变错误信息提示B. 改变命令提示符C. 改变一些终端参数D. 改变辅助命令提示符11.作为一个管理员,你希望在每一个新用户的目录下放一个文件 .bashrc ,那么你应该在哪个目录下放这个文件,以便于新用户创建主目录时自动将这个文件复制到自己的目录下。
C++11中using语法解析及用法
C++11中using语法解析及⽤法⼀、using的所有语法功能using这个关键字当然不是在C++11中添加的,但的确是在C++11中扩展了这个关键字的意义,其中最关键的扩展就是增加alias这种语法意义。
直接查看gcc的代码,可以清晰的看到using关键字的所有⽤法及意义。
在gcc-4.9.0\gcc\cp\parser.c⽂件的cp_parser_block_declaration 函数中,即使通过注释也可以看到这个关键字的主要功能分为三种:using-declaration, a using-directive, or an alias-declaration。
三种语法的解析也⽐较直观:如果using后⾯直接跟着namespace关键字,则是⼀个directive;如果下⼀个是⼀个变量名并且第三个token是等号则认为是⼀种类型别名,否则落⼊第三种using声明。
static voidcp_parser_block_declaration (cp_parser *parser,bool statement_p){……/* If the next keyword is `using', we have ausing-declaration, a using-directive, or an alias-declaration. */else if (token1->keyword == RID_USING){cp_token *token2;if (statement_p)cp_parser_commit_to_tentative_parse (parser);/* If the token after `using' is `namespace', then we have ausing-directive. */token2 = cp_lexer_peek_nth_token (parser->lexer, 2);if (token2->keyword == RID_NAMESPACE)cp_parser_using_directive (parser);/* If the second token after 'using' is '=', then we have analias-declaration. */else if (cxx_dialect >= cxx11&& token2->type == CPP_NAME&& ((cp_lexer_peek_nth_token (parser->lexer, 3)->type == CPP_EQ)|| (cp_nth_tokens_can_be_attribute_p (parser, 3))))cp_parser_alias_declaration (parser);/* Otherwise, it's a using-declaration. */elsecp_parser_using_declaration (parser,/*access_declaration_p=*/false);}……}⼆、using declaration的解析及意义同样在不纠结细节的情况下,这⾥解析的⽅法就是⾸先解析所有的作⽤域(使⽤"::"表⽰),直到剩余最后⼀个identifier,这个identifier将会作为使⽤整个作⽤域的⼀个handle,其实从另⼀个⾓度看⼀认为是⼀个alias,或者是⽂件系统中的“链接”:因为本质上是通过⼀个较短的identifier名称来指代⼀个更长更完整的变量名。
qualvar R 包用户指南说明书
Package‘qualvar’October13,2022Type PackageTitle Implements Indices of Qualitative Variation Proposed by Wilcox(1973)Version0.2.0URL http://joelgombin.github.io/qualvar/BugReports https:///joelgombin/qualvar/issuesDescription Implements indices of qualitative variation proposed by Wilcox(1973).License GPL-3LazyData TRUEDepends R(>=2.10)Imports statsSuggests knitr,rmarkdown,dplyr,tidyr,ggplot2,GGally,DTVignetteBuilder knitr,rmarkdownRoxygenNote6.0.1NeedsCompilation noAuthor Joel Gombin[aut,cre]Maintainer Joel Gombin<*********************>Repository CRANDate/Publication2018-01-0300:12:05UTCR topics documented:ADA (2)B (3)DM (4)HREL (5)MDA (6)V A (7)wilcox1973 (8)12ADA Index9 ADA Average Deviation Analog(ADA)DescriptionComputes the average deviation analog(ADA)for a vector of frequencies of categories.UsageADA(x,na.rm=TRUE)Argumentsx a vector of frequenciesna.rm if TRUE,missing values are removed.If FALSE,NA is returned if there is any NA value.DetailsAccording to Wilcox(1973,p.328),the ADA is’an analog of the average or mean deviation’.Theformula for the ADA is:1− ki=1f i−NK2NK(K−1)ValueThe value of the ADA statistics,which is normalised(varies between0and1).ReferencesWilcox,Allen R.’Indices of Qualitative Variation and Political Measurement.’The Western Politi-cal Quarterly26,no.2(1June1973):325-43.doi:10.2307/446831.Examplesx<-rmultinom(1,100,rep_len(0.25,4))x<-as.vector(t(x))ADA(x)df<-rmultinom(10,100,rep_len(0.25,4))df<-as.data.frame(t(df))apply(df,1,ADA)B3B B(modified geometric mean)DescriptionComputes the B index for a vector of frequencies of categories.UsageB(x,na.rm=TRUE)Argumentsx a vector of frequenciesna.rm if TRUE,missing values are removed.If FALSE,NA is returned if there is any NA value.DetailsAccording to Wilcox(1973,p.330),and following Kaiser(1968),the B index relies on the geo-metric mean,but corrects it for undesirable properties.The formula for the B index is:1−1−Kki=1f i KN2ValueThe value of the B statistics,which is normalised(varies between0and1).ReferencesWilcox,Allen R.’Indices of Qualitative Variation and Political Measurement.’The Western Politi-cal Quarterly26,no.2(1June1973):325-43.doi:10.2307/446831.Kaiser,Henry F.’A Measure of the Population Quality of Legislative Apportionment.’The American Political Science Review 62,no.1(March1968):208.doi:10.2307/1953335.Examplesx<-rmultinom(1,100,rep_len(0.25,4))x<-as.vector(t(x))B(x)df<-rmultinom(10,100,rep_len(0.25,4))df<-as.data.frame(t(df))apply(df,1,B)4DM DM Deviation from the mode(DM)DescriptionComputes the deviation from the mode for a vector of frequencies of categories.UsageDM(x,na.rm=TRUE)Argumentsx a vector of frequenciesna.rm if TRUE,missing values are removed.If FALSE,NA is returned if there is any NA value.DetailsAccording to Wilcox(1973,p.327),’the measure can be thought of as an index of deviation from the modal frequency,analogous to the variance as a measure of deviation from the mean’.Theformula for the DM is:1− ki=1(f m−f i)N(K−1)ValueThe value of the DM statistics,which is normalised(varies between0and1).ReferencesWilcox,Allen R.’Indices of Qualitative Variation and Political Measurement.’The Western Politi-cal Quarterly26,no.2(1June1973):325-43.doi:10.2307/446831.Examplesx<-rmultinom(1,100,rep_len(0.25,4))x<-as.vector(t(x))names(x)<-c("a","b","c","d")DM(x)df<-rmultinom(10,100,rep_len(0.25,4))df<-as.data.frame(t(df))names(df)<-c("a","b","c","d")apply(df,1,DM)HREL5 HREL HRELDescriptionComputes the HREL index for a vector of frequencies of categories.UsageHREL(x,na.rm=TRUE)Argumentsx a vector of frequenciesna.rm if TRUE,missing values are removed.If FALSE,NA is returned if there is any NA value.DetailsAccording to Wilcox(1973,p.329),and following Senders(1958),the HREL is’a measure origi-nally developed by engineers for use in specifying the properties of communications channels.The rationale for HREL is presented in terms of guessing by Virginia Senders(supplementing the mode as best guess):"What we need is a measure of uncertainty,or of’poorness of a guess,’which will be high when the number of alternative possibilities is high,and low when some of the possibilities are much more likely than others.One possible measure is the average number of questions we have to ask to specify the correct alternative’.The formula for the HREL is:− ki=1f iNlog2f iNlog2KValueThe value of the HREL statistics,which is normalised(varies between0and1).ReferencesWilcox,Allen R.’Indices of Qualitative Variation and Political Measurement.’The Western Po-litical Quarterly26,no.2(1June1973):325-43.doi:10.2307/446831.Senders,Virginia L.Measurement and Statistics.New York:Oxford University Press,1958.Examplesx<-rmultinom(1,100,rep_len(0.25,4))x<-as.vector(t(x))HREL(x)df<-rmultinom(10,100,rep_len(0.25,4))df<-as.data.frame(t(df))apply(df,1,HREL)6MDA MDA Mean Difference Analog(MDA or MNDIF)DescriptionComputes the mean difference analog(MDA or MNDIF)for a vector of frequencies of categories.UsageMDA(x,na.rm=TRUE)Argumentsx a vector of frequenciesna.rm if TRUE,missing values are removed.If FALSE,NA is returned if there is any NA value.DetailsAccording to Wilcox(1973,p.328),the MDA is’an analog of the mean difference,a measure of variation that is discussed and used much less frequently than the average deviation or the standard deviation.It is defined as"the average of the differences of all the possible pairs of variate-values, taken regardless of sign"’.The formula for the MDA is:1− k−1i=1kj=i+1|f i−f j|N(K−1)ValueThe value of the MDA statistics,which is normalised(varies between0and1).ReferencesWilcox,Allen R.’Indices of Qualitative Variation and Political Measurement.’The Western Politi-cal Quarterly26,no.2(1June1973):325-43.doi:10.2307/446831.Examplesx<-rmultinom(1,100,rep_len(0.25,4))x<-as.vector(t(x))MDA(x)df<-rmultinom(10,100,rep_len(0.25,4))df<-as.data.frame(t(df))apply(df,1,MDA)V A7 VA Variance Analog(VA)DescriptionComputes the variance analog(V A)for a vector of frequencies of categories.UsageVA(x,na.rm=TRUE)Argumentsx a vector of frequenciesna.rm if TRUE,missing values are removed.If FALSE,NA is returned if there is any NA value.DetailsAccording to Wilcox(1973,p.329),the V A is’based on the variance,which is defined as the arithmetic mean of the squared differences of each value from the mean’.The formula for the V Ais:1− ki=1f i−NK2N2(K−1)KValueThe value of the V A statistics,which is normalised(varies between0and1).ReferencesWilcox,Allen R.’Indices of Qualitative Variation and Political Measurement.’The Western Politi-cal Quarterly26,no.2(1June1973):325-43.doi:10.2307/446831.Examplesx<-rmultinom(1,100,rep_len(0.25,4))x<-as.vector(t(x))VA(x)df<-rmultinom(10,100,rep_len(0.25,4))df<-as.data.frame(t(df))apply(df,1,VA)8wilcox1973 wilcox1973Results of the1968US presidential electionDescriptionA dataset containing the returns of the1968US presidential election,by states.Usagewilcox1973Formata data_frame with52rows and4variables.SourceWilcox,Allen R.’Indices of Qualitative Variation and Political Measurement.’The Western Politi-cal Quarterly26,no.2(1June1973):325-43.doi:10.2307/446831.Index∗datasetswilcox1973,8ADA,2B,3DM,4HREL,5MDA,6VA,7wilcox1973,89。
package中设置环境变量的几种方法
package中设置环境变量的几种方法在package中,我们经常需要设置环境变量来配置应用程序的行为。
在这篇文章中,我们将介绍几种在package中设置环境变量的方法。
第一种方法是使用`.env`文件。
这是一种常见的方式,可以在项目根目录下创建一个名为`.env`的文件,并在里面设置环境变量。
这些变量可以在整个应用程序中使用。
在`.env`文件中,每个环境变量都以`变量名=值`的形式进行设置,每个变量占据一行。
然后,在应用程序的入口文件中,通过引入`dotenv`包并调用`dotenv.config()`函数,可以将`.env`文件中的变量载入到环境中。
第二种方法是通过命令行参数设置环境变量。
在运行package命令时,可以使用`--env`参数来指定一个或多个环境变量。
例如,`package run --env VAR1=value1 VAR2=value2`。
这种方法适用于需要临时更改环境变量的情况,但不适用于长期配置。
第三种方法是在`package.json`文件中设置环境变量。
可以在`scripts`字段中的命令前面添加环境变量。
例如,`"start": "VAR1=value1 VAR2=value2 node index.js"`。
这样,在运行`package run start`命令时,这些环境变量将会传递给应用程序。
第四种方法是在命令行中直接设置环境变量。
可以在运行应用程序的命令之前使用`VAR1=value1 VAR2=value2`来设置环境变量。
例如,`VAR1=value1VAR2=value2 package run start`。
这种方法适用于需要手动设置环境变量的情况。
以上是在package中设置环境变量的几种方法。
根据具体需求,选择适合的方法可以更好地配置应用程序的行为。
通过使用这些方法,您可以方便地设置和管理环境变量,使应用程序具有更好的可配置性和灵活性。
R包cvar的简要指南说明书
Brief guide to R package cvarGeorgi N.BoshnakovUniversity of ManchesterAbstractPackage cvar is a small package with,essentially,two functions—ES()for computing the expected shortfall and VaR()for Value at Risk.The user specifies the distribution by supplyingone of the functions that define a continuous distribution—currently this can be a quantile function(qf),cumulative distribution function(cdf)or probability density function(pdf).Virtually anycontinuous distribution can be specified.This vignette is part of package cvar,version0.5.Keywords:expected shortfall,ES,CVaR,VaR,value at risk.1.IntroductionThere is a huge number of functions for computations with distributions in core R and in contributed packages.Pdf’s,cdf’s,quantile functions and random number generators are covered comprehensively. The coverage of expected shortfall is more patchy but a large collection of distributions,including functions for expected shortfall,is provided by Nadarajah,Chan,and Afuecheta(2013).Peterson and Carl(2018)and Dutang,Goulet,and Pigeon(2008)provide packages covering comprehensively various aspects of risk measurement,including some functions for expected shortfall.Package cvar is a small package with,essentially two functions—ES for computing the expected shortfall and VaR for Value at Risk.The user specifies the distribution by supplying one of the func-tions that define a continuous distribution—currently this can be a quantile function(qf),cumulative distribution function(cdf)or probability density function(pdf).Virtually any continuous distribution can be specified.The computations are done directly from the definitions,see e.g.Acerbi and Tasche (2002).The functions are vectorised over the parameters of the distributions,making bulk computations more convenient,for example for forecasting or model evaluation.The name of this package,”cvar”,comes from Conditional Value at Risk(CVaR),which is an alter-native term for expected shortfall.We chose to use the standard names ES and VaR,despite the possibility for name clashes with same named functions in other packages,rather than invent possibly difficult to remember alternatives.Just call the functions as cvar::ES and cvar::VaR if necessary.Locations-scale transformations can be specified separately from the other distribution parameters. This is useful when such parameters are not provided directly by the distribution at hand.The use of these parameters often leads to more efficient computations and better numerical accuracy even if the distribution has its own parameters for this purpose.Some of the examples for VaR and ES illustrate this for the Gaussian distribution.Since VaR is a quantile,functions computing it for a given distribution are convenience functions.VaR exported by cvar could be attractive in certain workflows because of its vectorised distribution pa-rameters,the location-scale transformation and the possibility to compute it from cdf’s when quantile functions are not available.2Brief guide to R package cvar2.Value at Risk and Expected ShortfallWe use the traditional definition of VaR as the negated lower quantile.More specifically,let Y be the variable of interes,such as return on afinancial asset.Suppose that it is modelled as a random variable with distribution function F Y(y).Then VaR is defined as1VaRα(Y)=−q Yα.where q Yαis the lowerα-quantile of Y,i.e.we haveα=F(q Yα)=P(Y≤q Yα).Typical values forαare0.05and0.01.Equivalently,we could write2VaRα(Y)=q−Y1−α.The expected shortfall is the(partial)expectation of VaRα(Y):ESα(Y)=1ααVaRγ(Y)dγ.Suppose now that Y is obtained from another random variable,X,by a linear transformation:Y=a+bXWhen this is the case,there is a simple relation between the VaR’s and ES’s of Y and X:VaRα(Y)=−a+b VaRα(X)ESα(Y)=−a+b ESα(X)In practice,X is often chosen to be standardised but this is not necessary.Note also that if a bunch of VaR’s and ES’s are needed,say for normally distributed variables,this can be computed very efficiently using this property.3.VaRHere we compute the VaR associated with a standard normal r.v.The three variants are equivalent since0.05and"qf"are default for the last two arguments.>cvar::VaR(qnorm,p_loss=0.05,dist.type="qf")[1]1.644854>cvar::VaR(qnorm,p_loss=0.05)[1]1.644854>cvar::VaR(qnorm)[1]1.644854x can be a vector:1Beware that a definition without negation is also used in both the literature and in the R packages.2This equation shows why some authors use the“big numbers”,e.g.0.95and0.99,in the notation for the VaR.Georgi N.Boshnakov3>cvar::VaR(qnorm,p_loss=c(0.01,0.05))[1]2.3263481.644854Let’s set some more realistic values for the parameters of the normal distribution.Suppose that thedaily returns on some stock have sample mean0.006408553and sample variance0.0004018977.ThenN(0.006408553,0.0004018977)can be taken as normal distributionfitted to the data.>muA<-0.006408553>sigma2A<-0.0004018977This computes VaR using thefitted normal distribution:>res1<-cvar::VaR(qnorm,p_loss=0.05,mean=muA,sd=sqrt(sigma2A))For the normal disribution we could also use the intercept-slope arguments,since the parameters are precisely the intercept and the slope:>res2<-cvar::VaR(qnorm,p_loss=0.05,intercept=muA,slope=sqrt(sigma2A))>abs((res2-res1))#0,intercept/slope equivalent to mean/sd[1]0If we compute VaR using the cdf,the intercept-slope method has some numerical advantage:>##with cdf the precision depends on solving an equation>res1a<-cvar::VaR(pnorm,p_loss=0.05,dist.type="cdf",+mean=muA,sd=sqrt(sigma2A))>res2a<-cvar::VaR(pnorm,p_loss=0.05,dist.type="cdf",+intercept=muA,slope=sqrt(sigma2A))>abs((res1a-res2))#3.287939e-09[1]3.287939e-09>abs((res2a-res2))#5.331195e-11,intercept/slope better numerically[1]5.331195e-11Of course,it is almost always better to use the quantile function when it is available.We can use smaller tollerance to improve the precision(the value.Machine$double.eps^0.75=1.81898940354586e-12is probably excessive):>##as above,but increase the precision,this is probably excessive>res1b<-cvar::VaR(pnorm,p_loss=0.05,dist.type="cdf",+mean=muA,sd=sqrt(sigma2A),tol=.Machine$double.eps^0.75)>res2b<-cvar::VaR(pnorm,p_loss=0.05,dist.type="cdf",+intercept=muA,slope=sqrt(sigma2A),tol=.Machine$double.eps^0.75) >abs((res1b-res2))#6.938894e-18#both within machine precision[1]6.938894e-18>abs((res2b-res2))#1.040834e-164Brief guide to R package cvar[1]1.040834e-16The relative precision is also good.>abs((res1b-res2)/res2)#2.6119e-16#both within machine precision[1]2.6119e-16>abs((res2b-res2)/res2)#3.91785e-15[1]3.91785e-15For examples with vectorised distribution parameters we use data from PerformanceAnalytics. Compute means and variances of the variables in a data frame and store them in vectors:>##if(require("PerformanceAnalytics")){>data(edhec,package="PerformanceAnalytics")>mu<-apply(edhec,2,mean)>sigma2<-apply(edhec,2,var)>musigma2<-cbind(mu,sigma2)We compute VaR using PerformanceAnalytics::VaR:>##analogous calc.with PerformanceAnalytics::VaR>vPA<-apply(musigma2,1,function(x)+PerformanceAnalytics::VaR(p=.95,method="gaussian",invert=FALSE,+mu=x[1],sigma=x[2],weights=1))The results below compare to the value,vPA,obtained here.The computations below are similar to the previous example but the distribution parameters are vectors.Thefirst pair of results are numerically the same:>vAz1<-cvar::VaR(qnorm,p_loss=0.05,mean=mu,sd=sqrt(sigma2))>vAz2<-cvar::VaR(qnorm,p_loss=0.05,intercept=mu,slope=sqrt(sigma2))>max(abs((vPA-vAz1)))#5.551115e-17[1]4.163336e-17>max(abs((vPA-vAz2)))#""[1]4.163336e-17Computing VaR from cdf shows some advantage for the location-scale method:>vAz1a<-cvar::VaR(pnorm,p_loss=0.05,dist.type="cdf",+mean=mu,sd=sqrt(sigma2))>vAz2a<-cvar::VaR(pnorm,p_loss=0.05,dist.type="cdf",+intercept=mu,slope=sqrt(sigma2))>max(abs((vPA-vAz1a)))#3.287941e-09[1]1.953409e-09Georgi N.Boshnakov5 >max(abs((vPA-vAz2a)))# 1.465251e-10,intercept/slope better[1]1.242979e-10The advantage remains for smaller tolerance:>vAz1b<-cvar::VaR(pnorm,p_loss=0.05,dist.type="cdf",+mean=mu,sd=sqrt(sigma2),+tol=.Machine$double.eps^0.75)>vAz2b<-cvar::VaR(pnorm,p_loss=0.05,dist.type="cdf",+intercept=mu,slope=sqrt(sigma2),+tol=.Machine$double.eps^0.75)>max(abs((vPA-vAz1b)))#4.374869e-13[1]4.831205e-14>max(abs((vPA-vAz2b)))#3.330669e-16[1]2.914335e-164.Expected shortfallES has essentially the same arguments as VaR.The examples below are obtained almost literally by replacing the calls to VaR with ES()ones.Here we compute the VaR associated with a standard normal r.v.The three variants are equivalent since0.5and"qf"are default for the last two arguments.>cvar::ES(qnorm,p_loss=0.05,dist.type="qf")[1]2.062713>cvar::ES(qnorm,p_loss=0.05)[1]2.062713>cvar::ES(qnorm)[1]2.062713x can be a vector:>cvar::ES(qnorm,p_loss=c(0.01,0.05))[1]2.6652142.062713Let’s set some more realistic values for the parameters of the normal distribution:>muA<-0.006408553>sigma2A<-0.00040189776Brief guide to R package cvarThis demonstrates the use of intercept and slope.These arguments use the linear transformation property discussed in the theoretical section.For the normal disribution the parameters are preciselythe intercept and the slope:>res1<-cvar::ES(qnorm,p_loss=0.05,mean=muA,sd=sqrt(sigma2A))>res2<-cvar::ES(qnorm,p_loss=0.05,intercept=muA,slope=sqrt(sigma2A))>abs((res2-res1))[1]9.714451e-17If we compute ES using the cdf,the intercept slope method has some numerical advantage:>##with cdf the precision depends on solving an equation>res1a<-cvar::ES(pnorm,p_loss=0.05,dist.type="cdf",+mean=muA,sd=sqrt(sigma2A))>res2a<-cvar::ES(pnorm,p_loss=0.05,dist.type="cdf",+intercept=muA,slope=sqrt(sigma2A))>abs((res1a-res2))#[1]1.933215e-10>abs((res2a-res2))#intercept/slope better numerically[1]2.385314e-13We can use smaller tollerance to improve the precision(the value.Machine$double.eps^0.75=1.81898940354586e-12is probably excessive):>##as above,but increase the precision,this is probably excessive>res1b<-cvar::ES(pnorm,p_loss=0.05,dist.type="cdf",+mean=muA,sd=sqrt(sigma2A),tol=.Machine$double.eps^0.75)>res2b<-cvar::ES(pnorm,p_loss=0.05,dist.type="cdf",+intercept=muA,slope=sqrt(sigma2A),tol=.Machine$double.eps^0.75) >abs((res1b-res2))[1]3.958639e-14>abs((res2b-res2))[1]6.938894e-16The relative precision is also good.>abs((res1b-res2)/res2)[1]1.13287e-12>abs((res2b-res2)/res2)[1]1.98575e-14Georgi N.Boshnakov7ReferencesAcerbi C,Tasche D(2002).“Expected shortfall:a natural coherent alternative to value at risk.”Economic notes,31(2),379–388.doi:10.1111/1468-0300.00091.URL https:///pdf/ cond-mat/0105191.pdf.Dutang C,Goulet V,Pigeon M(2008).“actuar:An R Package for Actuarial Science.”Journal of Statistical Software,25(7),38.URL /v25/i07.Nadarajah S,Chan S,Afuecheta E(2013).VaRES:Computes value at risk and expected shortfall for over100parametric distributions.R package version1.0,URL https:/// package=VaRES.Peterson BG,Carl P(2018).PerformanceAnalytics:Econometric Tools for Performance and Risk Analysis.R package version 1.5.2,URL https:///package= PerformanceAnalytics.Affiliation:Georgi N.BoshnakovSchool of MathematicsThe University of ManchesterOxford Road,Manchester M139PL,UKURL:/~gb/。
C#创建Excel(.xls和.xlsx)文件的三种方法
C#创建Excel(.xls和.xlsx)⽂件的三种⽅法⽣成EXCEL⽂件是经常需要⽤到的功能,我们利⽤⼀些开源库可以很容易实现这个功能。
⽅法⼀:利⽤excellibrary,excellibrary是国⼈写的开源组件,很容易使⽤,可惜貌似还不⽀持.xlsx(Excel 2007),例⼦如下://Create the data set and tableDataSet ds = new DataSet("New_DataSet");DataTable dt = new DataTable("New_DataTable");//Set the locale for eachds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;//Open a DB connection (in this example with OleDB)OleDbConnection con = new OleDbConnection(dbConnectionString);con.Open();//Create a query and fill the data table with the data from the DBstring sql = "SELECT Whatever FROM MyDBTable;";OleDbCommand cmd = new OleDbCommand(sql, con);OleDbDataAdapter adptr = new OleDbDataAdapter();adptr.SelectCommand = cmd;adptr.Fill(dt);con.Close();//Add the table to the data setds.Tables.Add(dt);//Here's the easy part. Create the Excel worksheet from the data setExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);例⼦⼆://create new xls filestring file = "C:\\newdoc.xls";Workbook workbook = new Workbook();Worksheet worksheet = new Worksheet("First Sheet");worksheet.Cells[0, 1] = new Cell((short)1);worksheet.Cells[2, 0] = new Cell(9999999);worksheet.Cells[3, 3] = new Cell((decimal)3.45);worksheet.Cells[2, 2] = new Cell("Text string");worksheet.Cells[2, 4] = new Cell("Second string");worksheet.Cells[4, 0] = new Cell(32764.5, "#,##0.00");worksheet.Cells[5, 1] = new Cell(DateTime.Now, @"YYYY\-MM\-DD");worksheet.Cells.ColumnWidth[0, 1] = 3000;workbook.Worksheets.Add(worksheet);workbook.Save(file);// open xls fileWorkbook book = Workbook.Load(file);Worksheet sheet = book.Worksheets[0];// traverse cellsforeach (Pair<Pair<int, int>, Cell> cell in sheet.Cells){dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;}// traverse rows by Indexfor (int rowIndex = sheet.Cells.FirstRowIndex;rowIndex <= stRowIndex; rowIndex++){Row row = sheet.Cells.GetRow(rowIndex);for (int colIndex = row.FirstColIndex;colIndex <= stColIndex; colIndex++){Cell cell = row.GetCell(colIndex);}}⽅法⼆:利⽤EPPlus,EPPlus是⼀个使⽤Open Office XML(xlsx)⽂件格式,能读写Excel 2007/2010 ⽂件的开源组件。
varoc包说明书
Package‘varoc’September4,2023Type PackageTitle Value Added Receiver Operating Characteristics CurveVersion0.1.0Date2023-09-01Description A continuous version of the receiver operating characteristics(ROC)curve to visual-ize and assess the classification and continuity performances of biomarkers,diagnos-tic tests,or risk prediction models.License GPL(>=2)Depends R(>=4.2.0),pROC,corrplot,grDevices,graphics,stats,utilsNeedsCompilation noAuthor Yunro Chung[aut,cre](<https:///0000-0001-9125-9277>)Maintainer Yunro Chung<*******************>Repository CRANDate/Publication2023-09-0409:10:02UTCR topics documented:amd (1)jdp (4)varoc (6)Index9 amd AMD:above mean differenceDescriptionSummary measures to evaluate the continuity performance of biomarkers,diagnostic tests,or risk prediction models.12amd Usageamd(y,x,fpf=0.3,pval="no",alternative="greater",B=2000,conf.level=0.95)Argumentsy binary output,where y=1if disease(or case)and y=0if non-disease(or control).x continuous score,e.g.biomarker,diagnostic test,risk score.fpf false positive fraction at which above mean difference is cacluated.pval"yes"for bootstrap p-value and bootstrap confidence interval.alternative alternative hypothesis:"greater""(default),"less","two.sided".B number of bootstrap samples.conf.level confidence level of bootstrap confidence interval.DetailsThe amd function summarizes a continuity performance of x at each cutoff c as:i)above mean difference(AMD),ii)intergrated AMD(IAMD),and iii)partial IAMD(PIAMD).For i),AMD(c) is true positive mean(TPM)(c)minus false positive mean(FPM)(c),where TPM(c)is E(x>c|y=1) and FPM(c)is E(x>c|y=0).For ii),the integreation of AMD over(-∞,∞).For iii),PIAMD is an intergreation of AMD over(-∞,c)divided by fpf.These measures can be viewed as continuous versions of ROC curve-based measures.Specifically, TPM(c)and FPM(c)are continuous versions of true positive fraction(TPF)(c)(or sensitivity(c)) and false positive fraction(FPF)(c)(or one minus specificity(c)),where TPF(c)=P(x>c|y=1)and FPF(c)=P(x>c|y=0).The useful(or useless)x has TPF(c)-FPF(c)>0and AMD(c)>0(or TPF(c)-FPF(c)=0and AMD(c)=0),although both can be negative.Similiarly,useful(or useless)x has area under the ROC curve(AUC)>0.5and IAMD(c)>0(or AUC=0.5and IAMD(c)=0)and/or(nor-malized)partial AUC(PAUC)>t/2and PIAMD(c)>0(or PAUC=t/2or PIAMD(c)=0).Here,partial PAUC is AUC a FPF range of0to fpf divided by fpf.The bootstrap p-value and confidence in-terval are computed under the null hypthesis:AMD(c)≤0,IAMD(c)≤0,or PIAMD(c)≤0,when pval="yes"and alterantive="greater".The threshold c is determined by setting an acceptable fpf,i.e.FPF(c)=fpf.Thus,i)is interpreted as AMD at a FPF of fpf,ii)is interprted as IAMD(or average AMD)at a FPF range of0and1,and iii)is interpreted as PIAMD(or average AMD)at a FPF of fpf or below.Thus,similar to AUC,ii) is a global measure.Similar to TPF and PAUC,i)and iii)are used when evaluating x at a specific range of FPFs is of interest.The varoc and jdp functions visualize them.Valuedf data frame with y and x.fpf false positive fraction at which above mean difference is cacluated.auc area under the ROC curve.pauc normalized partial aucres data frame with tpf,fpf,tpm,fpm,amd at each threshold(th))amd3amd data frame with tpf,fpf,tpm,fpf,amd,lcl,ucl,z,pvalue at FPF(th)=fpf,where lcl,ucl,z,pvalue are lower confidence limit,upper confidence limit,teststatis-tics,and p-value for AMD(th)based on B bootstrap samples.iamd data frame with tpf,fpf,tpm,fpf,amd,lcl,ucl,z,pvalue at FPF(th)=fpf,where lcl,ucl,z,pvalue are lower confidence limit,upper confidence limit,teststatis-tics,and p-value for IAMD(th)based on B bootstrap samples.piamd data frame with tpf,fpf,tpm,fpf,amd,lcl,ucl,z,pvalue at FPF(th)=fpf,where lcl,ucl,z,pvalue are lower confidence limit,upper confidence limit,teststatis-tics,and p-value for PIAMD(th)based on B bootstrap samples.Author(s)Yunro Chung[aut,cre]ReferencesDanielle Brister and Yunro Chung,Value added receiver operating characteristics curve(in-progress)Examplesset.seed(3)n1=50n0=50#1.marker1(useless biomaker)y1=c(rep(1,n1),rep(0,n0))x1=abs(c(rnorm(n1,0,1),rnorm(n0,0,1)))#1.1.amdfit1=amd(y=y1,x=x1,fpf=0.3)print(fit1)#1.2.varocvaroc(fit1)#1.3.jdpjdp(fit1)#2.marker2(useful biomarker)y2=y1x2=abs(c(rnorm(n1,1,1),rnorm(n0,0,1)))#2.1.amdfit2=amd(y=y2,x=x2,fpf=0.3)#2.2.varoc for marker1vs marker2amd.min=min(c(fit1$res$amd,fit2$res$amd))amd.max=max(c(fit1$res$amd,fit2$res$amd))varoc(fit1,amd.min=amd.min,amd.max=amd.max)4jdp varoc(fit2,amd.min=amd.min,amd.max=amd.max)#2.3.varoc for marker1vs marker2min=min(c(x1,x2))max=max(c(x1,x2))jdp(fit1,min=min,max=max)jdp(fit2,min=min,max=max)jdp JDP:jittered ot plotDescriptionJittered dot plot to visualize classification and continuity performances of biomarkers.Usagejdp(fit,min=NULL,max=NULL,eps=0.2,seed=1,main="JDP",ylab="x",xlab=c("y=0","y=1"),col=c("blue","red","gray","gray"),legend="top",lwd=1,lty=3,cex.main=1,cex.pt=1.5,b=1,cex.axis=1,cex.legend=1,digits=2)Argumentsfitfitted results from the amd()function in the varoc R package.min minimum value of y-axis.max maximum value of y-axis.eps jittered range of x-axis.seed seed number for jittering x-axis.main title for the plotylab title for the y axis.xlab title for the x axis.col colors to true positive,false negative,false positive,false negative.legend legend location,"bottomright","bottom","bottomleft","left","topleft","top", "topright","right"and"center".lwd line width.lty line type.cex.main main size.cex.pt point size.b label size.cex.axis axis size.cex.legend legend size.digits number of decimals.jdp5DetailsThe jdp function plots biomarker(or x)by jittered x-axis(y=0vs y=1)and visualizes its classifica-tion and continuity metrics.The vertical dotted line is the threshold corresponding to FPF=fpf,and the two horizontal lines at y=0and y=1are false positive and true positive means,respectively.See the amd function for more details.ValueNo return value,called for side effects.Author(s)Yunro Chung[aut,cre]ReferencesDanielle Brister and Yunro Chung,Value added receiver operating characteristics curve(in-progress)Examplesset.seed(3)n1=50n0=50#1.marker1(useless biomaker)y1=c(rep(1,n1),rep(0,n0))x1=abs(c(rnorm(n1,0,1),rnorm(n0,0,1)))#1.1.amdfit1=amd(y=y1,x=x1,fpf=0.3)print(fit1)#1.2.varocvaroc(fit1)#1.3.jdpjdp(fit1)#2.marker2(useful biomarker)y2=y1x2=abs(c(rnorm(n1,1,1),rnorm(n0,0,1)))#2.1.amdfit2=amd(y=y2,x=x2,fpf=0.3)#2.2.varoc for marker1vs marker2amd.min=min(c(fit1$res$amd,fit2$res$amd))amd.max=max(c(fit1$res$amd,fit2$res$amd))varoc(fit1,amd.min=amd.min,amd.max=amd.max)varoc(fit2,amd.min=amd.min,amd.max=amd.max)#2.3.varoc for marker1vs marker2min=min(c(x1,x2))max=max(c(x1,x2))jdp(fit1,min=min,max=max)jdp(fit2,min=min,max=max)varoc VAROC:value added receiver operating characteristics(ROC)curveDescriptionROC curve to visualize classification and continuity performances of biomarkers,diagnostic tests,or risk prediction models.Usagevaroc(fit,amd.min=NULL,amd.max=NULL,main="VAROC",ylab="True positive fraction",xlab="False positive fraction",col=c("#9932cc","#87ceeb","#ffe135","#f56642"),legend="right",lwd=1,cex.main=1,cex.axis=1,b=1,cex.legend=1,digits=2)Argumentsfitfitted results from the amd()function in the varoc R package.amd.min minimum value of AMD that is displayed on the plot.amd.max maximum value of AMD that is displayed on the plot.main title for the plotylab title for the y axis.xlab title for the x axis.col color that separates AMD on the plot.Default:c("#9932cc","#87ceeb","#ffe135","#f56642") legend legend location,"bottomright","bottom","bottomleft","left","topleft","top","topright","right"and"center".lwd line widthcex.main main size.cex.axis axis size.b label size.cex.legend legend size.digits number of decimals.DetailsThe varoc function plot true positive fraction(c)(or sensitivity(c))versus false positive fraction(c) (or one minus specificty(c))at each threshold c colored by above mean difference(c).See the amd fuction for more details.ValueNo return value,called for side effects.Author(s)Yunro Chung[aut,cre]ReferencesDanielle Brister and Yunro Chung,Value added receiver operating characteristics curve(in-progress) Examplesset.seed(3)n1=50n0=50#1.marker1(useless biomaker)y1=c(rep(1,n1),rep(0,n0))x1=abs(c(rnorm(n1,0,1),rnorm(n0,0,1)))#1.1.amdfit1=amd(y=y1,x=x1,fpf=0.3)print(fit1)#1.2.varocvaroc(fit1)#1.3.jdpjdp(fit1)#2.marker2(useful biomarker)y2=y1x2=abs(c(rnorm(n1,1,1),rnorm(n0,0,1)))#2.1.amdfit2=amd(y=y2,x=x2,fpf=0.3)#2.2.varoc for marker1vs marker2amd.min=min(c(fit1$res$amd,fit2$res$amd))amd.max=max(c(fit1$res$amd,fit2$res$amd))varoc(fit1,amd.min=amd.min,amd.max=amd.max)varoc(fit2,amd.min=amd.min,amd.max=amd.max)#2.3.varoc for marker1vs marker2 min=min(c(x1,x2))max=max(c(x1,x2))jdp(fit1,min=min,max=max)jdp(fit2,min=min,max=max)Indexamd,1jdp,4varoc,69。
IBM Cognos Transformer V11.0 用户指南说明书
sqlsugar的使用
sqlsugar是一个非常轻量级且强大的ORM,支持常见的数据库,例如Oracle,SqlServer,MySQL等。
在.NET中,可以通过以下步骤使用sqlsugar:1首先,你需要引入SqlSugar库。
你可以通过NuGet包管理器来安装,或者通过代码使用Package Manager Console 输入Install-Package SqlSugar命令进行安装。
2在代码中创建一个SqlSugarClient对象,这个对象会负责和数据库的交互。
csharpvar db = new SqlSugarClient(new ConnectionConfig(){ConnectionString = "你的数据库连接字符串",DbType = DbType.SqlServer, // 根据实际情况设置数据库类型IsAutoCloseConnection = true, // 连接使用完毕后自动关闭});3使用db对象来执行数据库操作。
例如,查询所有数据:csharpvar allStudents = db.Queryable<Student>().ToList();4插入数据:csharpvar student = new Student() { Name = "张三", Age = 18 };db.Insertable(student).ExecuteCommand();5更新数据:csharpvar student = db.Queryable<Student>().Where(it => it.Id == 1).FirstOrDefault();if (student != null) { = "李四";db.Updateable(student).ExecuteCommand();}6删除数据:csharpvar student = db.Queryable<Student>().Where(it => it.Id == 1).FirstOrDefault();if (student != null) {db.Deleteable(student).ExecuteCommand();}7事务处理:请注意,事务只能在同一个SqlSugarClient 对象中有效。
V8 R包说明说明书
Package‘V8’December4,2023Type PackageTitle Embedded JavaScript and WebAssembly Engine for RVersion4.4.1Description An R interface to V8<https://v8.dev>:Google's open source JavaScript and WebAssembly engine.This package can be compiled either with V8version6 and up or NodeJS when built as a shared library.License MIT+file LICENSEURL https://jeroen.r-universe.dev/V8BugReports https:///jeroen/v8/issuesSystemRequirements V8engine version6+is needed for ES6and W ASM support.On Linux you can build against libv8-dev(Debian)orv8-devel(Fedora).We also provide static libv8binaries formost platforms,see the README for details.NeedsCompilation yesVignetteBuilder knitrImports Rcpp(>=0.12.12),jsonlite(>=1.0),curl(>=1.0),utilsLinkingTo RcppSuggests testthat,knitr,rmarkdownRoxygenNote7.2.3Language en-USEncoding UTF-8Biarch trueAuthor Jeroen Ooms[aut,cre](<https:///0000-0002-4035-0289>), Jan Marvin Garbuszus[ctb]Maintainer Jeroen Ooms<*******************>Repository CRANDate/Publication2023-12-0413:30:02UTC12V8 R topics documented:JS (2)V8 (2)wasm (5)Index7 JS Mark character strings as literal JavaScript codeDescriptionThis function JS()marks character vectors with a special class,so that it will be treated as literal JavaScript code.It was copied from the htmlwidgets package,and does exactly the same thing.UsageJS(...)Arguments...character vectors as the JavaScript source code(all arguments will be pasted into one character string)Author(s)Yihui XieExamplesct<-v8()ct$eval("1+1")ct$eval(JS("1+1"))ct$assign("test",JS("2+3"))ct$get("test")V8Run JavaScript in a V8contextDescriptionThe v8()function(formerly called new_context)creates a new V8context.A context provides an execution environment that allows separate,unrelated,JavaScript code to run in a single instance of V8,like a tab in a browser.V83Usagev8(global="global",console=TRUE,typed_arrays=TRUE)engine_info()Argumentsglobal character vector indicating name(s)of the global e NULL for no name.console expose console API(console.log,console.warn,console.error).typed_arrays(deprecated)enable typed arrays in legacy libv8.Deprecated because typed arrays are natively supported in recent versions of libv8.DetailsA V8context cannot be saved or duplicated,but creating a new context and sourcing code is verycheap.You can run as many parallel v8contexts as you want.R packages that use V8can use a separate V8context for each object or function call.The name of the global object(i.e.global in node and window in browsers)can be set with the global argument.A context always have a global scope,even when no name is set.When a context is initiated with global=NULL,the global environment can be reached by evaluating this in the global scope,for example:ct$eval("Object.keys(this)").V8Context Methods##ctx<-v8()<V8engine11.7.439.16>$assign(name,value,auto_unbox=TRUE,...)$call(fun,...,auto_unbox=TRUE,await=FALSE)$console()$eval(src,serialize=FALSE,await=FALSE)$get(name,...,await=FALSE)$reset()$source(file)$validate(src)The ct$eval method evaluates a string of JavaScript code in the same way as eval in JavaScript.By default eval()returns a string with console output;but when the serialize parameter is set to TRUE it serializes the JavaScript return object to a JSON string or a raw buffer.The ct$get,ct$assign and ct$call functions automatically convert arguments and return value between R and JavaScript(using JSON).To pass literal JavaScript arguments that should not be converted to JSON,wrap them in JS(),see examples.If a call to ct$eval(),ct$get(),or ct$call()returns a JavaScript promise,you can set await= TRUE to wait for the promise to be resolved.It will then return the result of the promise,or an error in case the promise is rejected.The ct$validate function is used to test if a piece of code is valid JavaScript syntax within the context,and always returns TRUE or FALSE.4V8 In an interactive R session you can use ct$console()to switch to an interactive JavaScript console.Here you can use console.log to print objects,and there is some support for JS tab-completion.This is mostly for testing and debugging,it may not work perfectly in every IDE or R-frontend. Data InterchangeJSON is used for data interchange between R and JavaScript.Therefore you can(and should) only exchange data types that have a sensible JSON representation.One exception is raw vectors which are converted to/from Uint8Array buffers,see below.All other arguments and objects are automatically converted according to the mapping described in Ooms(2014),and implemented by the jsonlite package in fromJSON()and toJSON().As for version3.0of this R package,Raw vectors are converted to Uint8Array typed arrays,and vice versa.This makes it possible to efficiently copy large chunks binary data between R and JavaScript,which is useful for running wasm or emscripten.Note about Linux and Legacy V8enginesThis R package can be compiled against modern(V8version6+)libv8API,or the legacy libv8 API(V8version3.15and below).You can check V8::engine_info()to see the version that is running.The legacy version does not support modern JS(ES6)or W ASM,but it is still the default on older versions of Ubuntu and CentOS.The latest versions of all major Linux distributions now provide a modern version of V8.For Ubuntu16.04and18.04we provide backports of libv8(via libnode-dev),see the readme for details.ReferencesA Mapping Between JSON Data and R Objects(Ooms,2014):https:///abs/1403.2805Examples#Create a new contextctx<-v8();#Evaluate some codectx$eval("var foo=123")ctx$eval("var bar=456")ctx$eval("foo+bar")#Functions and closuresctx$eval("JSON.stringify({x:Math.random()})")ctx$eval("(function(x){return x+1;})(123)")#Objects(via JSON only)ctx$assign("mydata",mtcars)ctx$get("mydata")outlist<-ctx$get("mydata",simplifyVector=FALSE)outlist[1]#Assign JavaScriptctx$assign("foo",JS("function(x){return x*x}"))wasm5 ctx$assign("bar",JS("foo(9)"))ctx$get("bar")#Validate script without evaluatingctx$validate("function foo(x){2*x}")#TRUEctx$validate("foo=function(x){2*x}")#TRUEctx$validate("function(x){2*x}")#FALSE#Use a JavaScript libraryctx$source("https:///ajax/libs/underscore.js/1.13.6/underscore-min.js") ctx$call("_.filter",mtcars,JS("function(x){return x.mpg<15}"))#Example from underscore manualctx$eval("_.templateSettings={interpolate:/\\{\\{(.+?)\\}\\}/g}")ctx$eval("var template=_.template( Hello{{name}}! )")ctx$call("template",list(name="Mustache"))#Call anonymous functionctx$call("function(x,y){return x*y}",123,3)##Not run:#CoffeeScriptct2<-v8()ct2$source("/v1/browser-compiler/coffee-script.js")jscode<-ct2$call("pile","square=(x)->x*x",list(bare=TRUE)) ct2$eval(jscode)ct2$call("square",9)#Interactive consolect3<-v8()ct3$console()#//this is JavaScript#var test=[1,2,3]#JSON.stringify(test)#exit##End(Not run)wasm Experimental WebAssemblyDescriptionExperimental wrapper to load a WebAssembly program.Returns a list of exported functions.This will probably be moved into it’s own package once WebAssembly matures.Usagewasm(data)6wasm wasm_features()Argumentsdata either raw vector orfile path with the binary wasm programDetailsThe wasm_features()function uses the wasm-feature-detect JavaScript library to test which W ASM capabilities are supported in the current version of libv8.Examples#Load example wasm programinstance<-wasm(system.file( wasm/add.wasm ,package= V8 ))instance$exports$add(12,30)wasm_features()Indexengine_info(V8),2fromJSON(),4JS,2new_context(V8),2toJSON(),4V8,2v8(V8),2v8(),2wasm,4,5wasm_features(wasm),57。
STARTS模型函数包说明书
Package‘STARTS’October12,2022Type PackageTitle Functions for the STARTS ModelVersion1.3-8Date2022-05-1909:47:44Author Alexander Robitzsch[aut,cre](<https:///0000-0002-8226-3132>), Oliver Luedtke[aut](<https:///0000-0001-9744-3059>)Maintainer Alexander Robitzsch<**********************.de>Description Contains functions for estimating the STARTS model ofKenny and Zautra(1995,2001)<DOI:10.1037/0022-006X.63.1.52>,<DOI:10.1037/10409-008>.Penalized maximum likelihoodestimation and Markov Chain Monte Carlo estimation arealso provided,see Luedtke,Robitzsch and Wagner(2018)<DOI:10.1037/met0000155>.Depends R(>=3.1)Imports CDM(>=7.1-19),graphics,LAM(>=0.3-27),sirt(>=2.3),Rcpp,stats,utilsSuggests lavaanLinkingTo Rcpp,RcppArmadilloURL https:///alexanderrobitzsch/STARTS,https:///site/alexanderrobitzsch2/softwareLicense GPL(>=2)NeedsCompilation yesRepository CRANDate/Publication2022-05-1911:20:02UTCR topics documented:STARTS-package (2)data.starts (2)STARTS-utilities (5)starts_uni (6)1Index10STARTS-package Functions for the STARTS ModelDescriptionContains functions for estimating the STARTS model of Kenny and Zautra(1995,2001)<DOI:10.1037/0022-006X.63.1.52>,<DOI:10.1037/10409-008>.Penalized maximum likelihood estimation and MarkovChain Monte Carlo estimation are also provided,see Luedtke,Robitzsch and Wagner(2018)<DOI:10.1037/met0000155>.Author(s)Alexander Robitzsch[aut,cre](<https:///0000-0002-8226-3132>),Oliver Luedtke[aut](<https:///0000-0001-9744-3059>)Maintainer:Alexander Robitzsch<**********************.de>ReferencesKenny,D.A.,&Zautra,A.(1995).The trait-state-error model for multiwave data.Journal ofConsulting and Clinical Psychology,63,52-59.doi:10.1037/0022006X.63.1.52Kenny,D.A.,&Zautra,A.(2001).Trait-state models for longitudinal data.In L.M.Collins&A.G.Sayer(Eds.),New methods for the analysis of change(pp.243-263).Washington,DC,US:American Psychological Association.doi:10.1037/10409008Luedtke,O.,Robitzsch,A.,&Wagner,J.(2018).More stable estimation of the STARTS model:A Bayesian approach using Markov Chain Monte Carlo techniques.Psychological Methods,23(3),570-593.doi:10.1037/met0000155data.starts Datasets in the STARTS PackageDescriptionSome datasets for illustration used in the examples of the STARTS package.Usagedata(data.starts01a)data(data.starts01b)data(data.starts02)data(data.starts03a)data(data.starts03b)data(data.starts03c)Format•data.starts01a.A resimulated dataset containing three factors from the Big5scale mea-sured atfive time points used in Luedtke,Robitzsch and Wagner(2018).The dataset onlycontains observations without missing data.data.frame :890obs.of16variables:$id:int100006100008100010100014100032100033100035100038100049100050...$E1:num-0.281.480.12-1.05-0.28...$E2:num0.12-0.0920.495-0.679-0.467...$E3:num1.080.120.12-1.27-0.28...$E4:num0.4950.121.294-2.229-0.28...$E5:num-0.0920.7070.707-2.041-0.092...$N1:num1.114-0.173-0.0170.9581.27...$N2:num-0.3480.003-1.1671.6021.758...$N3:num-0.1920.471-0.3481.1140.627...$N4:num-0.348-1.167-0.5041.4261.27...$N5:num-0.192-0.836-0.1922.4211.27...$O1:num1.994-1.82-0.107-0.678-0.792...$O2:num1.423-0.678-0.678-0.6781.423...$O3:num1.423-1.066-0.6780.0750.852...$O4:num-0.29-0.678-0.290.075-0.107...$O5:num1.217-1.637-0.29-0.6780.646...•data.starts01b.Like data.starts01a,but the dataset also contains cases with missingdata.data.frame :3215obs.of17variables:$id:int100001100002100003100004100005100006100007100008100009100010...$patt:Factor w/26levels"P00010","P00011",..:24192025222618261926...$E1:num0.3081.670.3080.308-0.468...$E2:num0.3080.8950.7070.7070.120.12NA-0.092-0.280.496...$E3:num0.895NA NA0.895NA...$E4:num NA NA NA0.4960.496...$E5:num0.707NA0.308NA0.496-0.092-0.280.707NA0.707...$N1:num0.783-0.017-0.192-0.017-0.504...$N2:num1.114-0.348-0.348-0.348-0.836...$N3:num-0.348NA NA-0.348NA...$N4:num NA NA NA-0.504-1.811...$N5:num0.471NA-0.192NA-1.421...$O1:num-0.495-0.107-0.4951.035-0.792...$O2:num-0.107-0.107-0.291.035-0.29...$O3:num0.464NA NA1.423NA...$O4:num NA NA NA1.4230.281...$O5:num0.646NA-1.066NA0.281...•data.starts02contrains means and covariance matrices of the study of Wu(2016)for theolder and the younger cohort(Table2).Variables a indicate item parcels of negative attitudefactor at six occasions.Variable b denotes the performance difficulty factor and variable c thesomatic factor.List of2$older_cohort:List of3..$nobs:num630..$mean:Named num[1:18]3.533.463.122.712.82.672.622.692.462.37... ....-attr(*,"names")=chr[1:18]"a1""a2""a3""a4".....$covmat: data.frame :18obs.of18variables:$younger_cohort:List of3..$nobs:num660..$mean:Named num[1:18]4.624.524.463.583.963.212.943.163.032.74... ....-attr(*,"names")=chr[1:18]"a1""a2""a3""a4".....$covmat: data.frame :18obs.of18variables:•data.starts03a contains data from Wagner,Luedtke and Trautwein(2016)of the total sam-ple.data.starts03b contains covariance matrices for both gender groups.data.starts03c contains covariance matrices for both groups of different levels of depression.The structure of data.starts03a isList of2$nobs:num4532$covmat:num[1:6,1:6]0.2360.1640.1470.1290.13.....-attr(*,"dimnames")=List of2....$:chr[1:6]"T1""T2""T3""T4".......$:chr[1:6]"T1""T2""T3""T4"...The structure of data.starts03b isList of2$female:List of2..$nobs:num2495..$covmat:num[1:6,1:6]0.220.1580.1390.180.116.......-attr(*,"dimnames")=List of2......$:chr[1:6]"T1""T2""T3""T4".........$:chr[1:6]"T1""T2""T3""T4"...$male:List of2..$nobs:num2037..$covmat:num[1:6,1:6]0.250.1650.1520.130.147.......-attr(*,"dimnames")=List of2......$:chr[1:6]"T1""T2""T3""T4".........$:chr[1:6]"T1""T2""T3""T4"...The structure of data.starts03c isList of2$high:List of2..$nobs:num1342..$covmat:num[1:6,1:6]0.240.1720.1530.1910.127.......-attr(*,"dimnames")=List of2......$:chr[1:6]"T1""T2""T3""T4".........$:chr[1:6]"T1""T2""T3""T4"...$low:List of2STARTS-utilities5 ..$nobs:num1742..$covmat:num[1:6,1:6]0.2130.120.1180.1090.12.......-attr(*,"dimnames")=List of2......$:chr[1:6]"T1""T2""T3""T4".........$:chr[1:6]"T1""T2""T3""T4"...ReferencesLuedtke,O.,Robitzsch,A.,&Wagner,J.(2018).More stable estimation of the STARTS model:A Bayesian approach using Markov Chain Monte Carlo techniques.Psychological Methods,23(3),570-593.doi:10.1037/met0000155Wagner,J.,Luedtke,O.,&Trautwein,U.(2016).Self-esteem is mostly stable across young adult-hood:Evidence from latent STARTS models.Journal of Personality,84(4),523-535.doi:10.1111/ jopy.12178Wu,P.-C.(2016).Longitudinal stability of the Beck Depression Inventory II:A latent trait-state-occasion model.Journal of Psychoeducational Assessment,34,39-53.doi:10.1177/0734282915582101STARTS-utilities Utility Functions in the STARTS PackageDescriptionUtlity functions in the STARTS packageUsage##density inverse gamma distributiondigamma2(x,n0,var0)Argumentsx Numeric Vectorn0Prior sample sizevar0Prior variancestarts_uni Functions for the Univariate STARTS ModelDescriptionFunctions for computing the covariance matrix and simulating data from the univariate STARTS model(Kenny&Zautra,1995,2001).The STARTS model can be estimated with maximum likeli-hood,penalized maximum likelihood(i.e.,maximum posterior estimation)or Markov Chain Monte Carlo.See Luedtke,Robitzsch and Wagner(2018)for comparisons among estimation methods. Usage##estimation of univariate STARTS modelstarts_uni_estimate(data=NULL,covmat=NULL,nobs=NULL,estimator="ML", pars_inits=NULL,prior_var_trait=c(3,0.33),prior_var_ar=c(3,0.33),prior_var_state=c(3,0.33),prior_a=c(3,0.5),est_var_trait=TRUE,est_var_ar=TRUE,est_var_state=TRUE,var_meas_error=0,constraints=TRUE,time_index=NULL,type="stationary",n.burnin=5000,n.iter=20000,verbose=FALSE,optim_fct="optim",use_rcpp=TRUE)##S3method for class starts_unisummary(object,digits=3,file=NULL,print_call=TRUE,...)##S3method for class starts_uniplot(x,...)##S3method for class starts_unilogLik(object,...)##S3method for class starts_unicoef(object,...)##S3method for class starts_univcov(object,...)##computation of covariance matrixstarts_uni_cov(W,var_trait,var_ar,var_state,a,time_index=NULL,add_meas_error=NULL)##simulation of STARTS modelstarts_uni_sim(N,W,var_trait,var_ar,var_state,a,time_index=NULL)#---deprecated functionsstarts_cov(W,var_trait,var_ar,var_state,a)starts_sim1dim(N,W,var_trait,var_ar,var_state,a)Argumentsdata Data frame.Missing data must be coded as NA.covmat Covariance matrix(not necessary if data is provided)nobs Number of observations(not necessary if data is provided)estimator Type of estimator:"ML"for maximum likelihood estimation(using LAM::pmle),"PML"for penalized maximum likelihood estimation(using LAM::pmle)and"MCMC"for Markov chain Monte Carlo estimation(using LAM::amh).pars_inits Optional vector of initial parametersprior_var_traitVector of length two specifying the inverse gamma prior for trait variance.Thefirst entry is the prior sample size,the second entry the guess of the proportionof the variance that is attributed to the trait variance.See Luedtke et al.(2018)for further details.prior_var_ar Prior for autoregressive variance.See prior_var_trait for details.prior_var_statePrior for state variance.See prior_var_trait for details.prior_a Vector of length two for specification of the beta prior for stability parameter a.Thefirst entry corresponds to the prior sample size,the second entry correspondsto the prior guess of the stability parameter.est_var_trait Logical indicating whether the trait variance should be estimated.est_var_ar Logical indicating whether the autoregressive variance should be estimated.est_var_state Logical indicating whether the state variance should be estimated.var_meas_error Value of known measurement variance.Could be based on a reliability estimateof internal consistency,for example.constraints Logical indicating whether variances should be constrained to be positivetime_index Integer vector of time indices.Time points can be non-equidistant,but must beinteger values.type Type of starts model.Only"stationary"is implemented in this package ver-sion.n.burnin Number of burn-in iterations(if estimator="MCMC")n.iter Total number of iterations(if estimator="MCMC")verbose Logical indicating whether iteration progress should be displayed(if estimator="ML"or estimator="PML")optim_fct Type of optimization function if estimator="ML"or estimator="PML".Canbe"optim"for stats::optim or"nlminb"for stats::nlminb.use_rcpp Logical indicating whether Rcpp code should be used in estimation.W Number of measurement waves.var_trait Variance of trait component.var_ar Variance of autoregressive component.var_state Variance of state component.N Sample size of personsa Stability parameterobject Object of class starts_unidigits Number of digits after decimal in summary outputfile Optionalfile name for summary outputprint_call Logical indicating whether call should be printed in summary outputx Object of class starts_uni...Further arguments to be passed.For the plot method,see the plot method for the LAM::amh function for argumentsadd_meas_error Optional vector of measurement error variance which should be added to the diagonal of the covariance matrix.ValueOutput of starts_uni_estimatecoef Vector of estimated parameters...Further valuesOutput of starts_uni_cov is a covariance matrix.Output of starts_uni_sim is a data frame containing simulated values.ReferencesKenny,D.A.,&Zautra,A.(1995).The trait-state-error model for multiwave data.Journal of Consulting and Clinical Psychology,63,52-59.doi:10.1037/0022006X.63.1.52Kenny,D.A.,&Zautra,A.(2001).Trait-state models for longitudinal data.In L.M.Collins&A.G.Sayer(Eds.),New methods for the analysis of change(pp.243-263).Washington,DC,US:American Psychological Association.doi:10.1037/10409008Luedtke,O.,Robitzsch,A.,&Wagner,J.(2018).More stable estimation of the STARTS model:A Bayesian approach using Markov Chain Monte Carlo techniques.Psychological Methods,23(3),570-593.doi:10.1037/met0000155Exampleslibrary(sirt)##############################################################################EXAMPLE1:STARTS model specification using starts_uni_estimate###############################################################################use simulated dataset according to Luedtke et al.(2017)data(data.starts01a,package="STARTS")dat<-data.starts01a#---covariance matrix and number of observationscovmat<-stats::cov(dat[,paste0("E",1:5)])nobs<-nrow(dat)#***Model1a:STARTS model with ML estimationmod1a<-STARTS::starts_uni_estimate(covmat=covmat,nobs=nobs)summary(mod1a)##Not run:#-estimate model based on input datamod1a1<-STARTS::starts_uni_estimate(data=dat[,paste0("E",1:5)])summary(mod1a1)#***Model1b:STARTS model with penalized ML estimation using the default priors mod1b<-STARTS::starts_uni_estimate(covmat=covmat,nobs=nobs,estimator="PML") summary(mod1b)#***Model1c:STARTS model with MCMC estimation and default priorsset.seed(987)mod1c<-STARTS::starts_uni_estimate(covmat=covmat,nobs=nobs,estimator="MCMC")#assess convergenceplot(mod1c)#summarysummary(mod1c)#extract more informationlogLik(mod1c)coef(mod1c)vcov(mod1c)#***Model1d:MCMC estimation with different prior distributionsmod1d<-STARTS::starts_uni_estimate(covmat=covmat,nobs=nobs,estimator="MCMC", prior_var_trait=c(10,0.5),prior_var_ar=c(10,0.3),prior_var_state=c(10,0.2),prior_a=c(1,0.5))summary(mod1d)#***Model2:remove autoregressive processmod2<-STARTS::starts_uni_estimate(covmat=covmat,nobs=nobs,est_var_ar=FALSE) summary(mod2)#***Model3:remove stable trait factormod3<-STARTS::starts_uni_estimate(covmat=covmat,nobs=nobs,est_var_trait=FALSE) summary(mod3)#***Model4:remove state variance from the modelmod4<-STARTS::starts_uni_estimate(covmat=covmat,nobs=nobs,est_var_state=FALSE) summary(mod4)##End(Not run)Index∗packageSTARTS-package,2coef.starts_uni(starts_uni),6data.starts,2data.starts01a(data.starts),2data.starts01b(data.starts),2data.starts02(data.starts),2data.starts03a(data.starts),2data.starts03b(data.starts),2data.starts03c(data.starts),2digamma2(STARTS-utilities),5LAM::amh,7,8LAM::pmle,7logLik.starts_uni(starts_uni),6plot.starts_uni(starts_uni),6STARTS(STARTS-package),2STARTS-package,2STARTS-utilities,5starts_cov(starts_uni),6starts_sim1dim(starts_uni),6starts_uni,6starts_uni_cov(starts_uni),6starts_uni_estimate(starts_uni),6starts_uni_sim(starts_uni),6stats::nlminb,7stats::optim,7summary.starts_uni(starts_uni),6vcov.starts_uni(starts_uni),610。
VAR模型估计、检验与预测包说明书
Package‘V AR.etp’August31,2023Type PackageTitle V AR Modelling:Estimation,Testing,and PredictionVersion1.1Date2023-08-31Author Jae.H.KimMaintainer Jae H.Kim<********************>Description A collection of the functions for estimation,hypothesis testing,prediction for station-ary vector autoregressive models.License GPL-2NeedsCompilation noRepository CRANDate/Publication2023-08-3108:40:02UTCR topics documented:V AR.etp-package (2)dat (2)data1 (3)PR.Fore (3)PR.IARM (4)PR.order (5)Rmatrix (6)V AR.BaBPR (7)V AR.Boot (9)V AR.BPR (10)V AR.est (11)V AR.FOR (12)V AR.Fore (13)V AR.irf (14)V AR.LR (15)V AR.Pope (16)V AR.Rest (17)V AR.select (19)V AR.Wald (20)12dat Index22 VAR.etp-package VAR Modelling:Estimation,Testing,and PredictionDescriptionEstimation,Hypothesis Testing,Prediction in Stationary Vector Autoregressive ModelsDetailsPackage:V AR.etpType:PackageVersion: 1.1Date:2023-08-31License:GPL-2The data set dat.rda is from Lutkepohl’s book.It is German Macrodata in log difference.Bootstrap bias-correction and prediction intervals are also included.Estimation and Forecasting based on Predictive Regression is also included.Author(s)Jae H.KimMaintainer:Jae H.Kimdat German investment income consumption in log differenceDescriptionLutkepohl’s dataUsagedata(dat)ReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,SpringerExamplesdata(dat)data13 data1stock return data used in Kim(2014)Descriptionstock return data used in Kim(2014)Usagedata(data1)ReferencesKim,J.H.2014,Testing for parameter restrictions in a stationary V AR model:a bootstrap alterna-tive.Economic Modelling,41,267-273.Examplesdata(data1)PR.Fore Improved Augmented Regression Method for Predictive RegressionDescriptionFunction for forecasting based on Imporved ARMUsagePR.Fore(x,y,M,h=10)Argumentsx predictor or matrix of predictors in columny variable to be predicted,usually stock returnM Estimation results of the function PR.IARMh forecasting periodDetailsFunction for forecasting based on Imporved ARMValueFore Out-of sample and dynamic forecasts for y and x4PR.IARMNoteKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance25,13-15.Author(s)jae H.KimReferencesKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance25,13-15.Examplesdata(data1)#Replicating Table5(excess return)y=data1$ret.nyse.vw*100-data1$tbill*100x=cbind(log(data1$dy.nyse),data1$tbill*100);k=ncol(x)p=4Rmat1=Rmatrix(p,k,type=1,index=1);Rmat=Rmat1$Rmat;rvec=Rmat1$rvecM=PR.IARM(x,y,p,Rmat,rvec)PRF=PR.Fore(x,y,M)PR.IARM Improved Augmented Regression Method(IARM)for Predictive Re-gressionDescriptionFunction for Improved ARM(IARM)estimation and testingUsagePR.IARM(x,y,p,Rmat=diag(k*p),rvec=matrix(0,nrow=k*p)) Argumentsx predictor or a matrix of predictors in columny variable to be predicted,usually data1returnp AR orderRmat Restriction matrix,refer to function Rmatrixrvec Restriction matrix,refer to function RmatrixDetailsKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance,26,13-25.PR.order5ValueLS Ordinary Least Squares EstimatorsIARM IARM EstimatorsAR AR parameter estimatorsARc Bias-corrected AR parameter estimatorsFstats Fstats and their p-valuesCovbc Covariance matrix of the IARM estimators(for the predictive coefficients only) NoteKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance,26,13-25.Author(s)Jae H.KimReferencesKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance,26,13-25.Examplesdata(data1)#Replicating Table5(excess return)of Kim(2014)y=data1$ret.nyse.vw*100-data1$tbill*100x=cbind(log(data1$dy.nyse),data1$tbill*100);Rmat1=Rmatrix(p=1,k=2,type=1,index=0);Rmat=Rmat1$Rmat;rvec=Rmat1$rvecM=PR.IARM(x,y,p=1,Rmat,rvec)PR.order Improved Augmented Regression Method for Predictive RegressionDescriptionFunction to select the order p by AIC or BICUsagePR.order(x,y,pmax=10)Argumentsx predictor or a matrix of predictors in columny variable to be predicted,usually stock returnpmax maximum order for order selection6Rmatrix DetailsKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance25,13-15.Valuep.aic order chosen by AICp.aic order chosen by BICNoteKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance25,13-15.Author(s)Jae H.KimReferencesKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance25,13-15.Examplesdata(data1)#Replicating Table5(excess return)y=data1$ret.nyse.vw*100-data1$tbill*100x=cbind(log(data1$dy.nyse),data1$tbill*100);k=ncol(x)p=PR.order(x,y,pmax=10)$p.bic;#AR(1)Rmatrix Improved Augmented Regression Method for Predictive RegressionDescriptionFunction to generate restriction matricesUsageRmatrix(p,k,type=1,index=0)Argumentsp AR orderk number of predictorstype type=1:H0:b1=b2=b3=0;type=2:H0:b1+b2+b3=0index index=0:H0applies for all parameters;index=k:H0applies for kth predictorDetailsFunction to generate restriction matricesValueRmat this value should be passed to PR.IARMrvec this value should be passed to PR.IARMAuthor(s)Jae H.KimReferencesKim J.H.,2014,Predictive Regression:Improved Augmented Regression Method,Journal of Em-pirical Finance25,13-15.ExamplesRmat1=Rmatrix(p=1,k=1,type=2,index=1);Rmat=Rmat1$Rmat;rvec=Rmat1$rvecVAR.BaBPR Bootstrap-after-Bootstrap Prediction Intervals for VAR(p)ModelDescriptionBias-correction given with stationarity CorrectionUsageVAR.BaBPR(x,p,h,nboot=500,nb=200,type="const",alpha=0.95)Argumentsx data matrix in columnp AR orderh forecasting periodnboot number of2nd-stage bootstrap iterationsnb number of1st-stage bootstrap iterationstype"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendalpha100(1-alpha)percent prediction intervalsDetailsBias-correction given with stationarity CorrectionValueIntervals Prediction IntervalsForecast Point Forecastsalpha Probability Content of Prediction IntervalsNoteBias-correction given with stationarity CorrectionAuthor(s)Jae H.KimReferencesKim,J.H.(2001).Bootstrap-after-bootstrap prediction intervals for autoregressive models,Journal of Business&Economic Statistics,19,117-128.Examplesdata(dat)VAR.BaBPR(dat,p=2,h=10,nboot=200,nb=100,type="const",alpha=0.95)#nboot and nb are set to low numbers for fast execution in the example#In actual implementation,use higher numbers such as nboot=1000,nb=200V AR.Boot9 VAR.Boot Bootstrapping VAR(p)model:bias-correction based on the bootstrapDescriptionThe function returns bias-corrected parmater estimators and Bias estimators based on the bootstrapUsageVAR.Boot(x,p,nb=200,type="const")Argumentsx data matrix in columnp AR ordernb number of bootstrap iterationstype"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendDetailsKilian’s(1998)stationarity-correction is used for bias-correctionValuecoef coefficient matrixresid matrix of residualssigu residual covariance matrixBias Bootstrap Bias EstimatorAuthor(s)Jae H.KimReferencesKilian,L.(1998).Small sample confidence intervals for impulse response functions,The Review of Economics and Statistics,80,218-230.Examplesdata(dat)VAR.Boot(dat,p=2,nb=200,type="const")10V AR.BPR VAR.BPR Bootstrap Prediction Intervals for VAR(p)ModelDescriptionNo Bias-correction is givenUsageVAR.BPR(x,p,h,nboot=500,type="const",alpha=0.95)Argumentsx data matrix in columnp AR orderh forecasting periodnboot number of bootstrap iterationstype"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendalpha100(1-alpha)percent prediction intervalsDetailsBootstrap Prediction Intervals for V AR(p)ModelValueIntervals Prediction IntervalsForecast Point Forecastsalpha Probability Content of Prediction IntervalsNoteNo Bias-correction is givenAuthor(s)Jae H.KimReferencesKim,J.H.(2001).Bootstrap-after-bootstrap prediction intervals for autoregressive models,Journal of Business&Economic Statistics,19,117-128.V AR.est11Examplesdata(dat)VAR.BPR(dat,p=2,h=10,nboot=200,type="const",alpha=0.95)#nboot is set to a low number for fast execution in the example#In actual implementation,use higher number such as nboot=1000VAR.est Estimation of unrestricted VAR(p)model parametersDescriptionThis function returns least-squares estimation results for V AR(p)modelUsageVAR.est(x,p,type="const")Argumentsx data matrix in columnp AR ordertype"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendDetailsV AR estimationValuecoef coefficient matrixresid matrix of residualssigu residual covariance matrixzzmat data moment matrixzmat data moment matrixtratio matrix of tratio corresponding to coef matrixNoteSee Chapter3of Lutkepohl(2005)Author(s)Jae H.Kim12V AR.FORReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,SpringerExamples#replicating Section3.2.3of of Lutkepohl(2005)data(dat)M=VAR.est(dat,p=2,type="const")print(M$coef)print(M$tratio)VAR.FOR VAR ForecastingDescriptionGenerate point forecasts and prediction intervalsUsageVAR.FOR(x,p,h,type="const",alpha=0.95)Argumentsx data matrix in columnp V AR orderh Forecasting Periodstype"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendalpha100(1-alpha)percent prediction intervalsDetailsPrediction Intervals are based on normal approximationValueIntervals Prediction Intervals,out-of-sample and dynamicForecast Point Forecasts,out-of-sample and dynamicalpha Probability Content of Prediction Interva;sNoteSee Chapter3of Lutkepohl(2005)V AR.Fore13Author(s)Jae H.KimReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,SpringerExamples#replicating Section3.5.3of Lutkepohl(2005)data(dat)VAR.FOR(dat,p=2,h=10,type="const",alpha=0.95)VAR.Fore VAR ForecastingDescriptionGenerate point forecasts using the estimated V AR coefficient matrixUsageVAR.Fore(x,b,p,h,type="const")Argumentsx data matrix in columnb matrix of coefficients from V AR.est or V AR.Restp V AR orderh Forecasting Periodstype"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendDetailsGenerate point forecasts using the estimated V AR coefficient matrixValueFore Point Forecasts,out-of-sample and dynamicNoteSee Chapter3of Lutkepohl(2005)Author(s)Jae H.Kim14V AR.irfReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,SpringerExamples#replicating Section3.5.3of Lutkepohl(2005)data(dat)b=VAR.est(dat,p=2,type="const")$coefVAR.Fore(dat,b,p=2,h=10,type="const")VAR.irf Orthogonalized impluse response functions from an estimated VAR(p)modelDescriptionThis function returns Orthogonalized impluse response functionsUsageVAR.irf(b,p,sigu,h=10,graphs=FALSE)Argumentsb V AR coefficient matrix,from V AR.est or similar estimation functionp V AR ordersigu V AR residual covariance matrix,from V AR.est or similar estimation functionh response horizon,the default is set to10graphs logical,if TRUE,show the impulse-response functions,the default is FALSEDetailsV AR impulse response functionsValueimpmat matrix that contains orthogonalized impulse-responsesNoteSee Lutkepohl(2005)for detailsAuthor(s)Jae H.KimV AR.LR15ReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,SpringerExamples#replicating Table3.4and Figure3.11Lutkepohl(2005)data(dat)M=VAR.est(dat,p=2,type="const")b=M$coef;sigu=M$siguVAR.irf(b,p=2,sigu,graphs=TRUE)VAR.LR The Likelihood Ratio test for parameter restrictionsDescriptionLikelihood Ratio test for zero parameter restrictions based on system V AR estimationBootstrap option is available:iid bootstrap or wild bootstrapBootstrap is conducted under the null hypothesis using estimated GLS estimation:see Kim(2014) UsageVAR.LR(x,p,restrict0,restrict1,type="const",bootstrap=0,nb=500) Argumentsx data matrix in columnp V AR orderrestrict0Restriction matrix under H0restrict1Restriction matrix under H1,if"full",the full V AR is estimated under H1type"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendbootstrap0for no bootstrap;1for iid bootstrap;2for wild bootstrapnb the number of bootstrap iterationsDetailsRestriction matrix is of m by3matrix where m is the number of restrictions.A typical row of this matrix(k,i,j),which means that(i,j)element of Ak matrix is set to0.Ak is a V AR coefficient matrix (k=1,....p).The bootstrap test is conducted using the GLS estimation under the parameter restrictions implied by the null hypothesis:see Kim(2014)for details.Kim(2014)found that the bootstrap based on OLS can show inferior small sample properties.There are two versions of the bootstrap:thefirst is based on the iid resampling and the second based on wild bootstrapping.The Wild bootstrap is conducted with Mammen’s two-point distribution.16V AR.PopeValueLRstat LR test statisticpval p-value of the LR testBoot.pval p-value of the test based on bootstrappingNoteSee Chapter4of Lutkepohl(2005)Author(s)Jae H.KimReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,SpringerKim,J.H.2014,Testing for parameter restrictions in a stationary V AR model:a bootstrap alterna-tive.Economic Modelling,41,267-273.Examplesdata(dat)#replicating Table4.4of Lutkepohl(2005)restrict1="full";restrict0=rbind(c(4,1,1),c(4,1,2),c(4,1,3),c(4,2,1),c(4,2,2),c(4,2,3),c(4,3,1),c(4,3,2),c(4,3,3))VAR.LR(dat,p=4,restrict0,restrict1,type="const")VAR.Pope Bias-correction for VAR parameter estimators based on Pope’s for-mulaDescriptionThe function returns bias-corrected parmater estimators and Bias estimators based on Pope’s asymp-totic formulaUsageVAR.Pope(x,p,type="const")Argumentsx data matrix in columnp AR ordertype"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendDetailsKilian’s(1998)stationarity-correction is used for bias-correctionValuecoef Bias-corrected coefficient matrixresid matrix of residualssigu residual covariance matrixBias Bias EstimateAuthor(s)Jae H.KimReferencesKim,J.H.2004,Bias-corrected bootstrap prediction regions for Vector Autoregression,Journal of FOrecasting23,141-154.Kilian,L.(1998).Small sample confidence intervals for impulse response functions,The Review of Economics and Statistics,80,218-230.Nicholls DF,Pope AL.1988,Bias in estimation of multivariate autoregression.Australian Journal of Statistics,30A,296-309.Pope AL.1990.Biases of estimators in multivariate non-Gaussian autoregression,Journal of Time Series Analysis11,249-258.Examplesdata(dat)VAR.Pope(dat,p=2,type="const")VAR.Rest VAR parameter estimation with parameter restrictionsDescriptionEstimation of V AR with0restrictions on parametersUsageVAR.Rest(x,p,restrict,type="const",method="gls")Argumentsx data matrix in columnp V AR orderrestrict Restriction matrix under H0type"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendmethod"ols"for OLS estimation,"gls"for EGLS estimationDetailsRestriction matrix is of m by3matrix where m is the number of restrictions.A typical row of this matrix(k,i,j),which means that(i,j)element of Ak matrix is set to0.Ak is a V AR coefficient matrix (k=1,....p).Valuecoef coefficient matrixresid matrix of residualssigu residual covariance matrixzmat data matrixtstat matrix of tratio corresponding to coef matrixNoteSee Chapter5of LutkepohlAuthor(s)Jae H.KimReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,SpringerExamplesdata(dat)#replicating Section5.2.10of Lutkepohl(2005)restrict=rbind(c(1,1,2),c(1,1,3),c(1,2,1),c(1,2,2),c(1,3,1),c(2,1,1),c(2,1,2),c(2,1,3),c(2,2,2),c(2,2,3),c(2,3,1),c(2,3,3),c(3,1,1),c(3,1,2),c(3,1,3),c(3,2,1),c(3,2,2),c(3,2,3),c(3,3,1),c(3,3,3),c(4,1,2),c(4,1,3),c(4,2,1),c(4,2,2),c(4,2,3),c(4,3,1),c(4,3,2),c(4,3,3))M=VAR.Rest(dat,p=4,restrict,type="const",method="gls")print(M$coef)print(M$tstat)V AR.select19 VAR.select Order Selection for VAR modelsDescriptionAIC,HQ,or SC can be usedUsageVAR.select(x,type="const",ic="aic",pmax)Argumentsx data matrix in columntype"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendic choose one of"aic","sc","hq"pmax the maximum V AR orderDetailsOrder Section CriterionValueIC Values of information criterion for V AR modelsp AR order selectedNoteSee Chapter4of LutkepohlAuthor(s)JAe H.KimReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,SpringerExamplesdata(dat)#replicating Section4.3.1of Lutkepohl(2005)VAR.select(dat,pmax=4,ic="aic")20V AR.Wald VAR.Wald Wald test for parameter restrictionsDescriptionWald test for zero parameter restrictions based on system V AR estimationBootstrap option is available:iid bootstrap or wild bootstrapBootstrap is conducted under the null hypothesis using estimated GLS estimation:see Kim(2014) UsageVAR.Wald(x,p,restrict,type="const",bootstrap=0,nb=500)Argumentsx data matrix in columnp V AR orderrestrict Restriction matrix under H0type"const"for the AR model with intercept only,"const+trend"for the AR model with intercept and trendbootstrap0for no bootstrap;1for iid bootstrap;2for wild bootstrapnb the number of bootstrap iterationsDetailsRestriction matrix is of m by3matrix where m is the number of restrictions.A typical row of this matrix(k,i,j),which means that(i,j)element of Ak matrix is set to0.Ak is a V AR coefficient matrix (k=1,....p).Under H1,the model is full V AR.The bootstrap test is conducted using the GLS estimation under the parameter restrictions implied by the null hypothesis:see Kim(2014)for details.Kim(2014)found that the bootstrap based on OLS can show inferior small sample properties.There are two versions of the bootstrap:thefirst is based on the iid resampling and the second based on wild bootstrapping.The Wild bootstrap is conducted with Mammen’s two-point distribution.ValueFstat Wald test statisticpval p-value of the test based on F-distributionBoot.pval p-value of the test based on bootstrappingNoteSee Chapter3of LutkepohlV AR.Wald21Author(s)Jae H.KimReferencesLutkepohl,H.2005,New Introduction to Multiple Time Series Analysis,Springer.Kim,J.H.2014,Testing for parameter restrictions in a stationary V AR model:a bootstrap alterna-tive.Economic Modelling,41,267-273.Examplesdata(dat)#replicating Section3.6.2of Lutkepohl(2005)restrict=rbind(c(1,1,2),c(1,1,3),c(2,1,2),c(2,1,3))VAR.Wald(dat,p=2,restrict,type="const")Index∗packageVAR.etp-package,2∗tsdat,2data1,3PR.IARM,4PR.order,5Rmatrix,6VAR.BaBPR,7VAR.Boot,9VAR.BPR,10VAR.est,11VAR.FOR,12VAR.Fore,13VAR.irf,14VAR.LR,15VAR.Pope,16VAR.Rest,17VAR.select,19VAR.Wald,20∗ysPR.Fore,3dat,2data1,3PR.Fore,3PR.IARM,4PR.order,5Rmatrix,6VAR.BaBPR,7VAR.Boot,9VAR.BPR,10VAR.est,11VAR.etp(VAR.etp-package),2 VAR.etp-package,2VAR.FOR,12VAR.Fore,13VAR.irf,14VAR.LR,15VAR.Pope,16VAR.Rest,17VAR.select,19VAR.Wald,20 22。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
2.3 Restricted VARs . . . . . . . . . . . . . . . . . . . . . . . . 6
2.4 Diagnostic testing . . . . . . . . . . . . . . . . . . . . . . . 9
2.5 Causality Analysis . . . . . . . . . . . . . . . . . . . . . . . 15
The package’s code is purely written in R and S3-classes with methods have been utilised. It is shipped with a NAMESPACE and a ChangeLog file. It has dependencies to MASS (see Venables & Ripley [2002]) and strucchange (see Zeileis, Leisch, Hornik & Kleiber [2002]).
3 SVAR: Structural vector autoregressive models
24
3.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.2 Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
par One important characteristic of a VAR(p)-process is its stability. This
1Vectors are assigned by small bold letters and matrices by capital letters. Scalars are written out as small letters. which are possibly subscripted.
Contents
1 Introduction
2
2 VAR: Vector autoregressive models
2
2.1 Definition . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Estimation . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
2.6 Forecasting . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
2.7 Impulse respon. . . . . . . . . . 20
2.8 Forecast error variance decomposition . . . . . . . . . . . . 22
Using the vars package
Dr. Bernhard Pfaff, Kronberg im Taunus June 12, 2007
Abstract
The utilisation of the functions contained in the package ‘vars’ are explained by employing a data set of the Canadian economy. The package’s scope includes functions for estimating vector autoregressive (henceforth: VAR) and structural vector autoregressive models (henceforth: SVAR). In addition to the two cornerstone functions VAR() and SVAR() for estimating such models, functions for diagnostic testing, estimation of restricted VARs, prediction of VARs, causality analysis, impulse response analysis (henceforth: IRA) and forecast error variance decomposition (henceforth: FEVD) are provided too. In each section, the underlying concept and/or method is briefly explained, thereby drawing on the exibitions in Lu¨tkepohl [2006], Lu¨tkepohl, Kr¨atzig, Phillips, Ghysels & Smith [2004], Lu¨tkepohl & Breitung [1997], Hamilton [1994] and Watson [1994].
3.3 Impulse response analysis . . . . . . . . . . . . . . . . . . . 29
3.4 Forecast error variance decomposition . . . . . . . . . . . . 29
4 VECM to VAR
The vignette is structured as follows: the next section is entirely devoted to VARs (definition, estimation, restrictions, diagnostic testing, forecasting, IRA and FEVD). In the ensuing section the topic of SVAR is elucidated (definition, estimation, IRA and FEVD). Finally, the transformation of a VECM to a VAR in levels is exhibited with its associated methods and functions.
defined as:
yt = A1yt−1 + . . . + Apyt−p + ut ,
(1)
with Ai are (K × K) coefficient matrices for i = 1, . . . , p and ut is a
K-dimensional white noise process with time invariant positive definite covariance matrix E(utut) = Σu.1
2 VAR: Vector autoregressive models
2.1 Definition
In its basic form, a VAR consists of a set of K endogenous variables
yt = (y1t, . . . , ykt, . . . , yKt) for k = 1, . . . K. The VAR(p)-process is then
29
1
1 Introduction
Since the critique of Sims [1980] in the early eighties of the last century, VAR analysis has evolved as a standard instrument in econometrics for analysing multivariate time series. Because statistical tests are highly used in determining interdependencies and dynamic relationships between variables, it became soon evident to enrich this methodology by incorporating non-statistical a priori information, hence SVAR models evolved which try to bypass these shortcomings. At the same time as Sims jeopardised the paradigm of multiple structural equation models laid out by the Cowles Foundation in the fourties and fifties of the last century, Granger [1981] and Engle & Granger [1987] endowed econometricians with a powerful tool for modelling and testing economic relationships, namely, the concept of integration and and cointegration. Nowadays these traces of research are unified in the form of vector error correction and structural vector error correction models. Although these latter topics are left out in this vignette, the interested reader is referred to the monographies of Lu¨tkepohl [2006], Hendry [1995], Johansen [1995], Hamilton [1994], Banerjee, Dolado, Galbraith & Hendry [1993] and Pfaff [2006] for an exhibition of unit root tests and co-integration analysis in R.