<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom"><channel><title>R on 格物堂</title><link>https://gewutang.cn/categories/r/</link><description>Recent content in R on 格物堂</description><generator>Hugo -- gohugo.io</generator><language>zh-cn</language><lastBuildDate>Mon, 19 May 2014 00:00:00 +0000</lastBuildDate><atom:link href="https://gewutang.cn/categories/r/index.xml" rel="self" type="application/rss+xml"/><item><title>R数据库交互系列笔记：DBI包</title><link>https://gewutang.cn/2014/05/19/notes-on-dbi/</link><pubDate>Mon, 19 May 2014 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2014/05/19/notes-on-dbi/</guid><description>&lt;p&gt;DBI是DataBase Interface的简称，即数据库界面。这篇笔记的主要内容是讲一讲如何用R中的DBI包来与常见数据库进行交互。&lt;/p&gt;&#10;&lt;h3 id="1-简介"&gt;&lt;a href="#1-%e7%ae%80%e4%bb%8b" class="header-anchor"&gt;&lt;/a&gt;1 简介&#10;&lt;/h3&gt;&lt;p&gt;DBI定义了一个与RDBMS类型数据库进行通信的泛型接口，对于任意一个RDBMS，DBI都会有一个兼容的数据库驱动来实现对接。目前，其可用的驱动包括Oracle、MySQL和SQLite等。&lt;/p&gt;&#10;&lt;p&gt;理论上说，DBI的泛型接口允许我们同样的代码来跟不同的RDBMS进行通信。但实际应用的时候，还要看具体的RDBMS与SQL标准的是否完全相似，以及数据库开发者开发过程中是否避免使用RDBMS特有的一些功能。&lt;/p&gt;&#10;&lt;p&gt;下面以SQLite数据库为例说明一下。例子中用的是Affymetrix hgu95av2的微阵列芯片数据，用之前先加载相关的包。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(tools)&#10;library(&amp;quot;RBioinf&amp;quot;)&#10;library(&amp;quot;DBI&amp;quot;)&#10;library(&amp;quot;RSQLite&amp;quot;)&#10;dbPath &amp;lt;- &amp;quot;hgu95av2-sqlite.db&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="2-dbi连接sqlite数据库"&gt;&lt;a href="#2-dbi%e8%bf%9e%e6%8e%a5sqlite%e6%95%b0%e6%8d%ae%e5%ba%93" class="header-anchor"&gt;&lt;/a&gt;2 DBI连接SQLite数据库&#10;&lt;/h3&gt;&lt;p&gt;DBI连接RDBMS需要两步。第一步，用dbDriver函数创建一个适合的数据库驱动；第二步，用dbConnect函数创建数据库连接。具体到SQLite，只需要指定包含数据库的文件夹路径即可。而对于MySQL或者Oracle，则需要指定主机地址、用户名和密码等信息。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;drv &amp;lt;- dbDriver(&amp;quot;SQLite&amp;quot;)&#10;db &amp;lt;- dbConnect(drv, dbPath)&#10;db&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;dbDisconnect函数可以断开连接。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;dbDisconnect(db)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="3-查询数据库结构"&gt;&lt;a href="#3-%e6%9f%a5%e8%af%a2%e6%95%b0%e6%8d%ae%e5%ba%93%e7%bb%93%e6%9e%84" class="header-anchor"&gt;&lt;/a&gt;3 查询数据库结构&#10;&lt;/h3&gt;&lt;p&gt;可以用dbListTables和dbListFields函数来列出数据库中的表名以及各表对应的字段（列名）。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;db &amp;lt;- dbConnect(drv, dbPath)&#10;dbListTables(db)&#10;dbListFields(db, &amp;quot;go_probe&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="4-查询语句"&gt;&lt;a href="#4-%e6%9f%a5%e8%af%a2%e8%af%ad%e5%8f%a5" class="header-anchor"&gt;&lt;/a&gt;4 查询语句&#10;&lt;/h3&gt;&lt;p&gt;dbSendQuery函数可以执行任意SQL语句。返回的结果是DBI结果的子类，这个子类的结果可以用fetch函数来查询。为了节约内存，用不到的数据库查询对象可以用dbClearResult函数进行清除。&lt;/p&gt;&#10;&lt;p&gt;fetch函数可以将查询结果转为数据框。dbColumnInfo、dbGetRowsAffected和dbGetRowCount函数可以返回更多关于查询的信息。下面分别演示。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;sql &amp;lt;- &amp;quot;select affy_id, evi from go_probe&amp;quot;&#10;rs &amp;lt;- dbSendQuery(db, sql)&#10;rs&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;DBIResult实例包含了查询的相关信息。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;dbColumnInfo(rs)&#10;dbGetStatement(rs)&#10;dbGetRowsAffected(rs)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;具体的结果可用fetch函数查看。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;chunk &amp;lt;- fetch(rs, n = 5)&#10;chunk&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;dbGetRowCount函数范围所有查询结果的行数。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;dbGetRowCount(rs)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;当不再用某个DBIResult实例时，记得清除。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;dbClearResult(rs)&#10;rs&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="5-基于查询结果构建r中的数据对象"&gt;&lt;a href="#5-%e5%9f%ba%e4%ba%8e%e6%9f%a5%e8%af%a2%e7%bb%93%e6%9e%9c%e6%9e%84%e5%bb%bar%e4%b8%ad%e7%9a%84%e6%95%b0%e6%8d%ae%e5%af%b9%e8%b1%a1" class="header-anchor"&gt;&lt;/a&gt;5 基于查询结果构建R中的数据对象&#10;&lt;/h3&gt;&lt;pre&gt;&lt;code class="language-r"&gt;sql &amp;lt;- &amp;quot;select * from go_probe&amp;quot;&#10;rs &amp;lt;- dbSendQuery(db, sql)&#10;dat &amp;lt;- fetch(rs, n = 500)&#10;goList &amp;lt;- split(dat$go_id, dat$affy_id)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="6-odbc"&gt;&lt;a href="#6-odbc" class="header-anchor"&gt;&lt;/a&gt;6 ODBC&#10;&lt;/h3&gt;&lt;p&gt;RODBC包可以连接ODBC数据源，当然前提是安装相应的数据库驱动。R导入与导出中给出了一些使用RODBC的实例，可以供参考。用ODBC连接RDBMS时，需要指定一个ODBC数据服务，具体如何做要看所用的操作系统。&lt;/p&gt;&#10;&lt;p&gt;RBioinf包中提供Gavin和Ho提供关于AP-MS蛋白质实验结果数据，分别给出了pcomplex.txt和pcomplex.xls两种格式，下面用它来演示下RODBC的用法。&lt;/p&gt;&#10;&lt;p&gt;数据包括三列：bait-protein，experiment和prey-protein。下面的结果仅在Windows系统下才能重现。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(&amp;quot;RODBC&amp;quot;)&#10;if (.Platform$OS.type == &amp;quot;Windows&amp;quot;) {&#10; pcomplexXls &amp;lt;- system.file(&amp;quot;extdata/pcomplex.xls&amp;quot;, package = &amp;quot;RBioinf&amp;quot;)&#10; db &amp;lt;- odbcConnectExcel(pcomplexXls)&#10; }&#10;if (!is.null(db)) {&#10; sqlTables(db)&#10; sqlQuery(db, &amp;quot;select * from [Sheet1$] limit 5&amp;quot;)&#10; }&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="7-参考文献"&gt;&lt;a href="#7-%e5%8f%82%e8%80%83%e6%96%87%e7%8c%ae" class="header-anchor"&gt;&lt;/a&gt;7 参考文献&#10;&lt;/h3&gt;&lt;p&gt;Seth Falcon，How to Use DBI: Connecting to Databases with R，January 17, 2006。&lt;/p&gt;&#10;</description></item><item><title>R中的金融数据接口</title><link>https://gewutang.cn/2013/11/05/financial-data-accessible-from-r/</link><pubDate>Tue, 05 Nov 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/11/05/financial-data-accessible-from-r/</guid><description>&lt;p&gt;借助R软件，我们可以从网站上获取很多经济和金融数据。我整理了一下目前R可以使用的获取金融数据的包，供大家参考。&lt;/p&gt;&#10;&lt;table&gt;&#10;&#9;&lt;thead&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;th&gt;数据源&lt;/th&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;th&gt;金融工具类型&lt;/th&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;th&gt;R包&lt;/th&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;th&gt;免费&lt;/th&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;th&gt;是否发布在CRAN上&lt;/th&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;th&gt;链接&lt;/th&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&lt;/thead&gt;&#10;&#9;&lt;tbody&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;yahoo&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;所有金融工具，日数据&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;quantmod&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;&lt;a class="link" href="http://www.quantmod.com" target="_blank" rel="noopener"&#10; &gt;http://www.quantmod.com&lt;/a&gt;&lt;/td&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;google&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;所有金融工具，财务数据，日数据&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;quantmod&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;&lt;a class="link" href="http://www.quantmod.com" target="_blank" rel="noopener"&#10; &gt;http://www.quantmod.com&lt;/a&gt;&lt;/td&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;Oanda&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;外汇、贵金属数据&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;quantmod&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;&lt;a class="link" href="http://www.quantmod.com" target="_blank" rel="noopener"&#10; &gt;http://www.quantmod.com&lt;/a&gt;&lt;/td&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;Fred&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;经济数据&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;quamod&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;&lt;a class="link" href="http://www.quantmod.com" target="_blank" rel="noopener"&#10; &gt;http://www.quantmod.com&lt;/a&gt;&lt;/td&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;Quandl&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;期货数据，日数据&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;RQuandl&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;http://quandl/help/packages/r&lt;/td&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;TrueFX&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;外汇高频数据&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;TFX&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;是&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;&lt;a class="link" href="http://rpubs.com/gsee/TFX" target="_blank" rel="noopener"&#10; &gt;http://rpubs.com/gsee/TFX&lt;/a&gt;&lt;/td&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;Bloomberg&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;所有品种、基金、所有频度&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;Rbbg&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;否&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;否&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;&lt;a class="link" href="http://finddata.org/rbloomberg/" target="_blank" rel="noopener"&#10; &gt;http://finddata.org/rbloomberg/&lt;/a&gt;&lt;/td&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&#9;&#9;&lt;tr&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;Interactive Broker&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;所有品种、所有频度&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;IBrokers&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;否&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;yes&lt;/td&gt;&#10;&#9;&#9;&#9;&#9;&#9;&lt;td&gt;&lt;a class="link" href="https://www.interactivebrokers.com" target="_blank" rel="noopener"&#10; &gt;www.interactivebrokers.com&lt;/a&gt;&lt;/td&gt;&#10;&#9;&#9;&#9;&lt;/tr&gt;&#10;&#9;&lt;/tbody&gt;&#10;&lt;/table&gt;&#10;</description></item><item><title>安装RMySQL</title><link>https://gewutang.cn/2013/09/28/notes-on-rmysql/</link><pubDate>Sat, 28 Sep 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/09/28/notes-on-rmysql/</guid><description>&lt;p&gt;处理金融市场数据的时候会用到MySQL数据库，R提供了一个RMySQL`包作为自身跟MySQL的接口。这个包本身很容易用，唯一不足的一点是在Windows下面安装RMySQL有点麻烦。安装RMySQL时,除了按部就班的安装MySQL、R、RTools、RMySQL等之外还要设置各种path变量以及把某些文件夹在各个路径里来回移动。&lt;/p&gt;&#10;&lt;p&gt;这篇文章就说一下自己在安装RMySQL过程中总结出来的较优的安装步骤。&lt;/p&gt;&#10;&lt;h4 id="下载并安装-mysql"&gt;&lt;a href="#%e4%b8%8b%e8%bd%bd%e5%b9%b6%e5%ae%89%e8%a3%85-mysql" class="header-anchor"&gt;&lt;/a&gt;下载并安装 MySQL&#10;&lt;/h4&gt;&lt;p&gt;下载并安装 &lt;a class="link" href="http:http://dev.mysql.com/downloads/mysql/" target="_blank" rel="noopener"&#10; &gt;MySQL&lt;/a&gt; ，这一点大多数人都知道如何操作，只提醒一点看清楚自己的电脑是 32位还是64位.&lt;/p&gt;&#10;&lt;h4 id="把mysql添加到path变量"&gt;&lt;a href="#%e6%8a%8amysql%e6%b7%bb%e5%8a%a0%e5%88%b0path%e5%8f%98%e9%87%8f" class="header-anchor"&gt;&lt;/a&gt;把MySQL添加到Path变量.&#10;&lt;/h4&gt;&lt;p&gt;具体做法是找到我的电脑(指图标)，右键，系统属性，打开&amp;quot;高级&amp;quot;选项卡，下面可以瞅见&amp;quot;环境变量&amp;quot;，点进去，上面部分为&amp;quot;用户变量&amp;quot;，下面部分是&amp;quot;系统变量&amp;quot;，在变量列，找到一个叫Path的东西，选中，点编辑，把MySQL的安装路径复制进去即可。&lt;/p&gt;&#10;&lt;h4 id="关联mysql和r软件"&gt;&lt;a href="#%e5%85%b3%e8%81%94mysql%e5%92%8cr%e8%bd%af%e4%bb%b6" class="header-anchor"&gt;&lt;/a&gt;关联MySQL和R软件&#10;&lt;/h4&gt;&lt;p&gt;具体是，打开 C:\Program Files\MySQL\MySQL Server 5.5\lib ，新建 OPT 文件夹，并复制 MYSQLLIB.LIB 到该文件夹内。同时，复制 libmysql.dll 到到\R\R-2.14.0\bin\ (64 bit) 或 \R\R-2.14.0\bin\i386\ (32 bit) 和 C:\Windows\System32 中;接下来,找到 R\3.0.2\etc 文件夹，并新建 Renviron.site 文件,用记事本打开,向其中添加一行:MYSQL_HOME =”C:/Program Files/MySQL/MySQL Server 5.5/” .&lt;/p&gt;&#10;&lt;h4 id="下载并安装rtools"&gt;&lt;a href="#%e4%b8%8b%e8%bd%bd%e5%b9%b6%e5%ae%89%e8%a3%85rtools" class="header-anchor"&gt;&lt;/a&gt;下载并安装&lt;a class="link" href="http://cran.r-project.org/bin/windows/Rtools/" target="_blank" rel="noopener"&#10; &gt;RTools&lt;/a&gt;&#10;&lt;/h4&gt;&lt;p&gt;安装过程很简单。要提醒的是要把\Rtools\2.14\bin,\Rtools\3.0.x\MinGW\bin,\Rtools\3.0.x\MinGW64\bin 添加到 path 变量。&lt;/p&gt;&#10;&lt;h4 id="下载rmysql源代码"&gt;&lt;a href="#%e4%b8%8b%e8%bd%bdrmysql%e6%ba%90%e4%bb%a3%e7%a0%81" class="header-anchor"&gt;&lt;/a&gt;下载&lt;a class="link" href="http://biostat.mc.vanderbilt.edu/wiki/main/RMySQL/RMySQL_0.8-0.tar.gz" target="_blank" rel="noopener"&#10; &gt;RMySQL&lt;/a&gt;源代码&#10;&lt;/h4&gt;&lt;p&gt;略过。&lt;/p&gt;&#10;&lt;h4 id="运行代码安装rmysql"&gt;&lt;a href="#%e8%bf%90%e8%a1%8c%e4%bb%a3%e7%a0%81%e5%ae%89%e8%a3%85rmysql" class="header-anchor"&gt;&lt;/a&gt;运行代码安装RMySQL&#10;&lt;/h4&gt;&lt;p&gt;假设源码存放地址为 d://RMySQL_0.8-0.tar.gz ,运行如下命令:&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;install.packages(&amp;quot;RMySQL_0.8-0.tar.gz&amp;quot;,repo=NULL,type=&amp;quot;source&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;测试安装是否成功:&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(RMySQL) &#10;drv = dbDriver(&amp;quot;MySQL&amp;quot;) &#10;con = dbConnect(drv,host=&amp;quot;localhost&amp;quot;,dbname=&amp;quot;test&amp;quot;,user=&amp;quot;root&amp;quot;,pass=&amp;quot;root&amp;quot;) &#10;album = dbGetQuery(con,statement=&amp;quot;select * from t_master&amp;quot;) &#10;album&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>R软件中的集合计算操作</title><link>https://gewutang.cn/2013/09/27/notes-on-sets-caculations-in-r/</link><pubDate>Fri, 27 Sep 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/09/27/notes-on-sets-caculations-in-r/</guid><description>&lt;p&gt;在处理数据尤其是在编写函数或编译R包的时候会涉及到集合的运算操作。比如，判断某个元素是否属于某个集合，并用这个判断结果作为 if 结构中的条件语句。&lt;/p&gt;&#10;&lt;p&gt;在量化投资的编程中更是经常用到集合的运算操作。比如，判断某支股票是否在今日的投资组合里，又或者在已有当前投资组合的情况下如何生成交易单以得到理想投资组合的股票代码，这涉及到差集操作。因此，了解一下R中的集合计算操作是很有必要的。&lt;/p&gt;&#10;&lt;p&gt;根据小学时候的知识，我们知道集合计算无非包括这么几类：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;两个集合的交集，即两个集合中共有的那些元素&lt;/li&gt;&#10;&lt;li&gt;两个集合的并集，即两个集合粗暴合并，并剔除重复值后剩余的那些元素&lt;/li&gt;&#10;&lt;li&gt;两个集合的差集，集合1减去集合1跟集合2的交集，即得到集合1、集合2的差集，换句话说，集合1中包含而集合2未包含的那些元素&lt;/li&gt;&#10;&lt;li&gt;元素判断，即开篇说的那个问题，某个元素是否属于某个集合&lt;/li&gt;&#10;&lt;li&gt;集合等价判断，即两个集合是否是同一个集合&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;它们对应的R函数就是下面这些：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;union(x, y)&lt;/li&gt;&#10;&lt;li&gt;intersect(x, y)&lt;/li&gt;&#10;&lt;li&gt;setdiff(x, y)&lt;/li&gt;&#10;&lt;li&gt;is.element(el, set)&lt;/li&gt;&#10;&lt;li&gt;setequal(x, y)&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;本着解释知识不举例子就是耍流氓的精神，我们看看下面的例子:&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 随意生成两个向量x和y&#10;x &amp;lt;- c(sort(sample(1:20, 9)), NA)&#10;y &amp;lt;- c(sort(sample(3:23, 7)), NA)&#10;# 查看 x，y 都长什么样子&#10;x&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 4 6 7 9 11 15 17 19 NA&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;y&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 12 13 14 15 19 20 21 NA&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 计算并集&#10;union(x, y)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 4 6 7 9 11 15 17 19 NA 12 13 14 20 21&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 计算交集&#10;intersect(x, y)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 15 19 NA&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 计算差集，注意：计算差集时，集合的先后顺序是影响结果滴！&#10;setdiff(x, y)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 4 6 7 9 11 17&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;setdiff(y, x)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 12 13 14 20 21&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# x，y是否相等，当然不相等啦....&#10;setequal(x, y)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] FALSE&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 看看并集、交集、差集的关系&#10;## True for all possible x &amp;amp; y :&#10;setequal( union(x, y),&#10; c(setdiff(x, y), intersect(x, y), setdiff(y, x)))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] TRUE&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 元素判断&#10;is.element(5, x)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] FALSE&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;is.element(100, x)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] FALSE&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;is.element(x, y) # length 10&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] FALSE FALSE FALSE FALSE FALSE FALSE TRUE FALSE TRUE TRUE&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;is.element(y, x) # length 8&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] FALSE FALSE FALSE TRUE TRUE FALSE FALSE TRUE&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>WDI包：从世界银行获取世界发展指标数据</title><link>https://gewutang.cn/2013/09/09/notes-on-wdi/</link><pubDate>Mon, 09 Sep 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/09/09/notes-on-wdi/</guid><description>&lt;p&gt;在网络上闲逛时偶然发现了WDI包，这个包可以帮助我们搜索、提取及格式化世界银行（World Bank）公布的世界发展指标（World Development Indicators）数据。&lt;/p&gt;&#10;&lt;p&gt;WDI包包括一个数据对象WDI_data及三个函数 WDIsearch、WDIcache和WDI。其中，WDI是主函数，WDIsearch和WDIcache是辅助函数。&lt;/p&gt;&#10;&lt;p&gt;WDI_data作为一个本地对象，保存了世界银行截止2012年6月18日所有可获得的指标信息。&lt;/p&gt;&#10;&lt;p&gt;WDIcache函数作用是更新可获得的WDI的指标列表。从世界银行网站上下载一个WDI指标的列表。返回一个数据框，该数据框可以作为WDIsarch函数的对象。从世界银行网站下载所有的时序信息会非常耗时间。用来对wDI_data对象中的信息进行更新。通过 cache 函数输入到WDIsearch函数中。&lt;/p&gt;&#10;&lt;p&gt;WDIseach函数的作用是搜索所有WDI序列的名字和信息描述。搜索WDI序列的代码、名字、描述及数据源。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; WDIsearch(string = &amp;quot;gdp&amp;quot;, field = &amp;quot;name&amp;quot;, short = TRUE,&#10; cache = NULL)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;string 搜索关键字&#10;field 搜索范围&amp;rsquo;indicator&amp;rsquo;, &amp;rsquo;name&amp;rsquo;, &amp;lsquo;description&amp;rsquo;, &amp;lsquo;sourceDatabase&amp;rsquo;, &amp;lsquo;sourceOrganization&amp;rsquo;等。&#10;short 逻辑变量。TRUE，只返回代码和名字。FALSE返回序列的所有信息。&#10;cache WDIcache函数生成的数据列表。缺失的话，WDIsearch会在本地的数据列表中进行查询。&lt;/p&gt;&#10;&lt;p&gt;返回的是满足特定搜索条件的序列的代码、名字、数据源及序列描述。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;WDIsearch(string='gdp', field='name', cache=NULL)&#10;WDIsearch(string='AG.AGR.TRAC.NO', field='indicator', cache=NULL)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;使用世界银行的API获取需要的数据，解析生成的JSON文件并将结果整理为包含国家和年份信息的长格式数据。&lt;/p&gt;&#10;</description></item><item><title>add.indicator函数笔记</title><link>https://gewutang.cn/2013/09/01/notes-on-add.indicator/</link><pubDate>Sun, 01 Sep 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/09/01/notes-on-add.indicator/</guid><description>&lt;p&gt;add.indicator函数是quantstrat包中的主函数之一。它的主要功能是生成信号指示器。这种解释方法有点绕口。举个例子说起来更容易明白。假如说，我们想测试这样一个策略：即当某支股票的价格低于5日算术平均时，买入该股票；高于5日算术平均时卖出该股票。那么，在这个测试过程中，我们要用到 SMA(price,n=5) 这个序列（SMA函数的作用是计算算术平均），既然要用到这个序列，那么得首先生成这个序列， add.indicator函数就是干这个的，是用来生成序列的。&lt;/p&gt;&#10;&lt;p&gt;看看帮助文档中的 add.indicator 函数的参数：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;add.indicator(strategy, name, arguments,&#10; parameters = NULL, label = NULL, ..., enabled = TRUE,&#10; indexnum = NULL, store = FALSE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;strategy参数是策略名。在quantstrat 包的框架中，所有指示器（indicator）都从属于策略（strategy），因此，使用add.indicator函数时要率先指定策略名；name参数的作用是指定生成指示器所用的R函数，比如，这里我们用到的函数是SMA ，那么，此时的name参数就是SMA；arguments参数也是个从属参数，它的作用是指定name 参数对应的那个函数的参数。好绕口！说人话的话是这样的：SMA函数除了要输入时间序列参数x 外，还得指定做算术平均时候的时间跨度n，而这个n就是在aruments中指定的。label参数的作用是设定指示器的标签，这样在生成指示器序列时，指示器的序列名的后缀会是该标签的内容。该参数默认是 name+ind。其它参数暂时不怎么重要，就不闲扯了，多说无益，上代码：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;##定义一个策略，名字名为 str_sma &#10;strategy(&amp;quot;str_sma&amp;quot;, store=TRUE)&#10;##获取策略的标的，名字为 SPY&#10;getSymbols(&amp;quot;SPY&amp;quot;, src='yahoo')&#10;##添加指示器&#10;add.indicator('str.sma', 'SMA', arguments=list(x=quote(Ad(SPY)), n=20),label=&amp;quot;sma.20&amp;quot;)&#10;##查看策略的结构&#10;str(getStrategy('str.sma')$indicators)&#10;## 执行指示器&#10;out &amp;lt;- applyIndicators('str.sma', SPY)&#10;## 查看指示器结果&#10;tail(out)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>时空数据可视化</title><link>https://gewutang.cn/2013/07/28/the-visualization-of-spatual-temporal-data/</link><pubDate>Sun, 28 Jul 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/07/28/the-visualization-of-spatual-temporal-data/</guid><description>&lt;p&gt;这几天北京有点热，穿着汗衫都觉得浑身冒烟儿，做啥都没有激情，只能赖在家里或者躲进图书馆和博物馆。没什么紧要的事情都懒得往外面走，但一月一次的“COS数据分析沙龙”是个例外。没有紧要的事儿，都得抽出时间去参加，偶尔还得客串一下主持人。&lt;/p&gt;&#10;&lt;p&gt;这次沙龙的主题是“时空数据的可视化”，分享嘉宾是来自中科院地理所的王江浩（@沐洲），整个沙龙内容真的令人震撼。&lt;/p&gt;&#10;&lt;p&gt;我第一次对江浩有印象是在微博上。二〇一三年三月，上海爆发H9N7疫情，之后不久江苏、浙江等省份相继出现疫情。一时间全国上下议论纷纷，专家、民众都担心这次疫情会酿成第二次SARS（非典型性肺炎）。很多人都开始关注H9N7的疫情趋势，就在这个时候，江浩的微博开始贴出H9N7疫情的可视化图，且被大量转发。&lt;/p&gt;&#10;&lt;p&gt;再不久，雅安发生地震，江浩根据网上抓取的地震相关数据，对雅安周边的地区震级做了相当经典的可视化，从地图上标注了雅安周边地区各个县、乡的地震成度。让人对当地情况一目了然。我也是第一次感觉到了时空数据可视化的重要性。&lt;/p&gt;&#10;&lt;p&gt;细想之下，何止地震和疫情呢？交通情况也是时空数据可视化中的重点。此外，还有经济学中的时空经济学，也可以研究经济体在时空中的发展变化。我感觉，时空数据可视化对于国家宏观管理意义非凡。&lt;/p&gt;&#10;</description></item><item><title>修改chartSeries绘图结果的x轴标签</title><link>https://gewutang.cn/2013/06/26/change-xlabels-in-chartseries/</link><pubDate>Wed, 26 Jun 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/06/26/change-xlabels-in-chartseries/</guid><description>&lt;p&gt;用quantmod包中的chartSeries绘图时，x轴标签会默认为中文汉字，看起来不太美观。想要修改制图结果吧，chartSeries函数中没有提供可设置x.labels的参数。原来chartSeries函数会自动识别系统语言并根据系统语言生成x.labels。这样的话，只要我们把自己的系统语言更改为英语，就应该显示为更为整洁的英文了。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;require(quantmod)&#10;getSymbols(&amp;quot;AAPL&amp;quot;)&#10;chartSeries(AAPL,theme=&amp;quot;white&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;Sys.setlocale(&amp;quot;LC_TIME&amp;quot;,&amp;quot;english&amp;quot;)&#10;chartSeries(AAPL,theme=&amp;quot;white&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;不过，这个好像不怎么重要吧？&lt;/p&gt;&#10;</description></item><item><title>R中的金融分析包：quantmod学习笔记补充版</title><link>https://gewutang.cn/2013/06/12/notes-on-quantmod/</link><pubDate>Wed, 12 Jun 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/06/12/notes-on-quantmod/</guid><description>&lt;p&gt;很久之前在&lt;a class="link" href="http://cos.name" target="_blank" rel="noopener"&#10; &gt;统计之都&lt;/a&gt;&lt;a class="link" href="http://cos.name/cn" target="_blank" rel="noopener"&#10; &gt;论坛&lt;/a&gt; 发了一个&lt;code&gt;quantmod&lt;/code&gt;包的学习笔记。听说后来流传很广泛。因为当时我也是初学&lt;code&gt;quantmod&lt;/code&gt;，所以，该版本笔记中有很多错漏之处，同时笔记的叙述结构也不太合理。一直我都想修订一版出来作为补充。修订的版本现在在&lt;a class="link" href="https://github.com/dengyishuo/Notes/tree/master/quantmod" target="_blank" rel="noopener"&#10; &gt;这里&lt;/a&gt;可以看到。&lt;/p&gt;&#10;&lt;p&gt;供大家参考，如果有什么建议和意见，请不吝指正。&lt;/p&gt;&#10;</description></item><item><title>安装mgarch包终极解决方案</title><link>https://gewutang.cn/2013/06/10/recipe-about-mgarch/</link><pubDate>Mon, 10 Jun 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/06/10/recipe-about-mgarch/</guid><description>&lt;p&gt;&lt;code&gt;mgarch&lt;/code&gt;包是一个可以拟合和诊断&lt;code&gt;BEKK&lt;/code&gt;模型的&lt;code&gt;R&lt;/code&gt;包。包中的主函数很少，只有&lt;code&gt;mvBEKK.sim&lt;/code&gt;，&lt;code&gt;mvBEKK.diag&lt;/code&gt;，&lt;code&gt;mvBEKK.est&lt;/code&gt;三个。这三个函数各司其职，分别用来模拟&lt;code&gt;BEKK&lt;/code&gt;数据、诊断&lt;code&gt;BEKK&lt;/code&gt;模型、拟合&lt;code&gt;BEKK&lt;/code&gt;模型。照常理说，这样的包很好啦。就只有一样不好，作者自从2009年更新一次之后，再也不提供更新的&lt;code&gt;.zip&lt;/code&gt;包了。很多需要拟合&lt;code&gt;BEKK&lt;/code&gt;模型的同学急得团团转就是不知道怎么安装和使用这个包。这里提供三个方案：&lt;/p&gt;&#10;&lt;h3 id="方案一"&gt;&lt;a href="#%e6%96%b9%e6%a1%88%e4%b8%80" class="header-anchor"&gt;&lt;/a&gt;方案一：&#10;&lt;/h3&gt;&lt;p&gt;下载&lt;a class="link" href="http://sourceforge.net/projects/mgarch/?source=directory" target="_blank" rel="noopener"&#10; &gt;mgarch&lt;/a&gt;的源代码包&lt;code&gt;mgarch_0.00-1.tar.gz&lt;/code&gt;。解压缩到&lt;code&gt;R&lt;/code&gt;的当前工作文件夹中。如果不知道当前工作文件夹路径。敲入&lt;code&gt;get.wd()&lt;/code&gt;函数就可以看到了。解压缩之后，按照&lt;code&gt;mgarch-&amp;gt;&amp;gt;R&lt;/code&gt;的顺序打开文件夹，你会在R文件夹中看到好几个&lt;code&gt;.r&lt;/code&gt;格式的文件。用&lt;code&gt;source()&lt;/code&gt;函数载入进来就可以用了。&lt;/p&gt;&#10;&lt;h3 id="方案二"&gt;&lt;a href="#%e6%96%b9%e6%a1%88%e4%ba%8c" class="header-anchor"&gt;&lt;/a&gt;方案二：&#10;&lt;/h3&gt;&lt;p&gt;拿着mgarch包，按照&lt;a class="link" href="http://cos.name/2011/05/write-r-packages-like-a-ninja/" target="_blank" rel="noopener"&#10; &gt;开发R程序包之忍者篇&lt;/a&gt;自己编译&lt;a class="link" href="http://sourceforge.net/projects/mgarch/?source=directory" target="_blank" rel="noopener"&#10; &gt;mgarch&lt;/a&gt;包。&lt;/p&gt;&#10;&lt;h3 id="方案三"&gt;&lt;a href="#%e6%96%b9%e6%a1%88%e4%b8%89" class="header-anchor"&gt;&lt;/a&gt;方案三:&#10;&lt;/h3&gt;&lt;p&gt;这个方案跟方案二类似，也得先安装&lt;code&gt;Rtools&lt;/code&gt;，目的是可以编译源代码。同时，由于&lt;a class="link" href="http://sourceforge.net/projects/mgarch/?source=directory" target="_blank" rel="noopener"&#10; &gt;mgarch&lt;/a&gt;依赖于&lt;code&gt;zoo&lt;/code&gt;、&lt;code&gt;tseries&lt;/code&gt;、&lt;code&gt;mvnorm&lt;/code&gt;三个支撑包，所以，也得捎带手安装一下，并保证它们被升级了到合适的版本。接着，将&lt;code&gt;mgarch_0.00-1.tar.gz&lt;/code&gt;放到当前工作文件夹中（不知道当前工作文件夹是哪个？看方案一）。最后，敲入下面的代码：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;install.packages(&amp;quot;mgarch_0.00-1.tar.gz&amp;quot;,repos=NULL,type=&amp;quot;source&amp;quot;) ##安装源代码文件&#10;library(mgarch) ##查看是否可以使用&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>安装mgarchBEKK包</title><link>https://gewutang.cn/2013/06/08/how-to-install-mgarchbekk/</link><pubDate>Sat, 08 Jun 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/06/08/how-to-install-mgarchbekk/</guid><description>&lt;p&gt;&lt;code&gt;R&lt;/code&gt;中另外一个拟合&lt;code&gt;BEKK&lt;/code&gt;模型的包是&lt;code&gt;mgarchBEKK&lt;/code&gt;。这个包跟前面提到的&lt;code&gt;mgarch&lt;/code&gt;包类似。主函数也基本一样，分别是&lt;code&gt;mvBEKK.sim&lt;/code&gt;、&lt;code&gt;mvBEKK.est&lt;/code&gt;、&lt;code&gt;mvBEKK.diag&lt;/code&gt;等。这个包作者已经很久没有更新了，好像已经放弃更新。但是有不少人还想用它。我们现在能在&lt;code&gt;quantmod&lt;/code&gt;包的主页找到该包的源代码，但不巧的是源代码包中缺失了&lt;code&gt;namespace&lt;/code&gt;。不过，没关系，我们可以为其添加一个&lt;code&gt;namespace&lt;/code&gt;即可。添加完之后，压缩为&lt;code&gt;.tar&lt;/code&gt;格式的压缩包（已添加完&lt;code&gt;namespace&lt;/code&gt;的&lt;code&gt;mgarchBEKK&lt;/code&gt;可以到&lt;a class="link" href="https://github.com/dengyishuo/dengyishuo.github.com/blob/master/media/mgarchBEKK.tar" target="_blank" rel="noopener"&#10; &gt;这里&lt;/a&gt;下载），再按照前面提到的安装方式进行安装即可。&lt;/p&gt;&#10;</description></item><item><title>有用但不易被发现的R函数：file.choose</title><link>https://gewutang.cn/2013/06/03/useful-functions-in-r/</link><pubDate>Mon, 03 Jun 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/06/03/useful-functions-in-r/</guid><description>&lt;p&gt;用R进行数据分析的时候，常常需要从外部载入数据或者函数。比如，我们有一个名为&lt;code&gt;example.txt&lt;/code&gt;的数据位于E盘中的R文件夹中，我们可以用下面的命令把数据读取到R里：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;dat = read.table(&amp;quot;E://R/example.txt&amp;quot;,header=TRUE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;在同样的文件夹中，有一个现成的函数脚本文件命名为&lt;code&gt;fun.r&lt;/code&gt;，现在需要将其载入到R中使用。可以用下面的命令:&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;soure(&amp;quot;E://R/fun.r&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;上面这两种做法有一个共同点就是得记住文件的绝对路径。绝对路径短的话，没有任何问题。当绝对路径很长，长到记不清楚的时候就麻烦了。&lt;/p&gt;&#10;&lt;p&gt;一个偷懒的做法是使用&lt;code&gt;setwd()&lt;/code&gt;设定工作文件夹。比如，我们可以把R的工作路径设定为&lt;code&gt;E://R/&lt;/code&gt;：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;setwd(&amp;quot;E://R/&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;然后，载入数据或者函数就可以用简化的命令了：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;source(&amp;quot;fun.r&amp;quot;)&#10;dat &amp;lt;- read.table(&amp;quot;example.txt&amp;quot;,header=TRUE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;如果连&lt;code&gt;E://R/&lt;/code&gt;都记不清楚呢？那就只能搞一个浏览窗口了。R中恰好有这个函数：&lt;code&gt;file.choose()&lt;/code&gt;&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;source(file.choose())&#10;dat &amp;lt;- read.table(file.choose(),header=TRUE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;运行之后，R会弹出一个&lt;code&gt;Select File&lt;/code&gt;的小窗口，挥动鼠标就可以对各个盘符和文件夹进行选择了。&lt;/p&gt;&#10;</description></item><item><title>自动下载财务套表</title><link>https://gewutang.cn/2013/05/27/download-financial-sheets/</link><pubDate>Mon, 27 May 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/05/27/download-financial-sheets/</guid><description>&lt;p&gt;在国内获取上市公司的财务数据是一件叫人头疼的事儿。对于没有Wind终端的个人而言，只有一条路：那就是从网络上抓取。当然，这还是有前提的，那就是网上得有数据可抓。很长一段时间，我都受此困扰，跋山涉水之后，终于从sina财经找到了一个可以下载上市公司历年财务套表的接口，用R写一段自动下载的代码，就可以轻松获取上市公司财务数据了（耶！好开心，妈妈再也不用担心我的的数据来源了！）。&lt;/p&gt;&#10;&lt;p&gt;代码真相在这里：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# symbol：股票代码&#10;# type：报表类型。BS为资产负债表；PS为利润表；CF为现金流量表&#10;# file:存储下载文件的地址。比如，file=&amp;quot;D://&amp;quot;&#10;&#10;getsheets &amp;lt;- function(symbol,type,file){&#10; pre=&amp;quot;http://money.finance.sina.com.cn/corp/go.php/vDOWN_&amp;quot;;&#10; mid=&amp;quot;/displaytype/4/stockid/&amp;quot;;&#10; end=&amp;quot;/ctrl/all.phtml&amp;quot;;&#10; &#10; if(type==&amp;quot;BS&amp;quot;){&#10; url=paste(pre,&amp;quot;BalanceSheet&amp;quot;,mid,symbol,end,sep=&amp;quot;&amp;quot;);&#10; destfile=paste(file,&amp;quot;BalanceSheet_&amp;quot;,symbol,&amp;quot;.xls&amp;quot;,sep=&amp;quot;&amp;quot;);&#10; }&#10; else if(type==&amp;quot;PS&amp;quot;){&#10; url=paste(pre,&amp;quot;ProfitStatement&amp;quot;,mid,symbol,end,sep=&amp;quot;&amp;quot;);&#10; destfile=paste(file,&amp;quot;ProfitStatement_&amp;quot;,symbol,&amp;quot;.xls&amp;quot;,sep=&amp;quot;&amp;quot;);&#10; }&#10; else if(type==&amp;quot;CF&amp;quot;){&#10; url=paste(pre,&amp;quot;CashFlow&amp;quot;,mid,symbol,end,sep=&amp;quot;&amp;quot;);&#10; destfile=paste(file,&amp;quot;CashFlow_&amp;quot;,symbol,&amp;quot;.xls&amp;quot;,sep=&amp;quot;&amp;quot;);&#10; }&#10; download.file(url, destfile);&#10;}&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;运行时如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 下载000065的资产负债表，并存放在D盘&#10;getsheets(&amp;quot;000065&amp;quot;,&amp;quot;BS&amp;quot;,&amp;quot;D://&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;D盘里面有一个叫BalanceSheet_000065.xls的文件，打开就可以看到历年的资产负债表数据了。&lt;/p&gt;&#10;</description></item><item><title>从东方财富网获取股票开户数据</title><link>https://gewutang.cn/2013/04/18/get-acount-data/</link><pubDate>Thu, 18 Apr 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/04/18/get-acount-data/</guid><description>&lt;p&gt;股票账户的开户数据对于观察和预测股票市场的冷热程度非常重要。但对于普通的投资人而言，由于没有专业的数据终端，他们是没有太多渠道可以获得股票开户数据的。好在一些网站上经常会公布股票开户数据，这样给普通投资者一个很好的渠道去获取数据。&lt;/p&gt;&#10;&lt;p&gt;目前，东方财富网的&lt;a class="link" href="https://data.eastmoney.com/cjsj/gpkhsj.html" target="_blank" rel="noopener"&#10; &gt;网页&lt;/a&gt;上就提供了逐月的股票账户开户数据，可以供普通投资者参考。&lt;/p&gt;&#10;&lt;p&gt;以前有人用R软件中的XML包去抓取上述网页。现在R软件中则提供了httr包和rvest包替代XML去抓取网页。不过，鉴于网站可能有严格的反爬虫机制，这种办法未必可以成功了。我还听说有人用RSelenium包获取网页上的表格数据，这个方案可能更复杂一些，但更可行。&lt;/p&gt;&#10;</description></item><item><title>几本关于R的书籍</title><link>https://gewutang.cn/2013/04/18/some-books-on-r/</link><pubDate>Thu, 18 Apr 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/04/18/some-books-on-r/</guid><description>&lt;p&gt;最近，出版社的朋友推荐了四本在亚马逊上卖的火热的R书籍。大致看了下内容，都算是上乘之作。这里简单介绍一下：&lt;/p&gt;&#10;&lt;p&gt;第一本叫《Introductory Time Series with R》。这是Springer出版社的UseR!系列作品，质量绝对是有保证的，内容集中于时间序列分析方面。作者是Paul S.P. Cowpertwait和Andrew V. Metcalfe 。&lt;/p&gt;&#10;&lt;p&gt;第二本是《Time Series Analysis: With Applications in R》是Springer统计学系列的一本书，也是专注于时间序列分析，这本书的厚度是第一本书的两倍。&lt;/p&gt;&#10;&lt;p&gt;第三本叫《Financial Risk Forecasting: The Theory and Practice of Forecasting Market Risk with Implementation in R and Matlab 》是Wiley出版社Finance Series系列的一本书，比较薄，内容主要集中在金融风险的预测上，更适合搞投资的人来阅读。&lt;/p&gt;&#10;&lt;p&gt;第四本是《Software for Data Analysis: Programming with R》是 Springer旗下Statistics and Computing系列的一般书，作者是R领域的大牛人叫John Chambers，我想他的名字是如雷贯耳的，无需多言，只需膜拜。&lt;/p&gt;&#10;</description></item><item><title>R中的量化投资包：quantstrat</title><link>https://gewutang.cn/2013/04/17/r%E4%B8%AD%E7%9A%84%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%8C%85quantstrat/</link><pubDate>Wed, 17 Apr 2013 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2013/04/17/r%E4%B8%AD%E7%9A%84%E9%87%8F%E5%8C%96%E6%8A%95%E8%B5%84%E5%8C%85quantstrat/</guid><description>&lt;h2 id="quantstrat是什么东西"&gt;&lt;a href="#quantstrat%e6%98%af%e4%bb%80%e4%b9%88%e4%b8%9c%e8%a5%bf" class="header-anchor"&gt;&lt;/a&gt;quantstrat是什么东西？&#10;&lt;/h2&gt;&lt;p&gt;quantstrat是Quantitative Strategy（量化策略）的缩写，它是由Peter Carl、 Brian G. Peterson、Josh Ulrich、Garrett See、Yu Chen等联合开发的用于量化投资的R包。&lt;/p&gt;&#10;&lt;p&gt;这个包为用户提供了一个测试和模拟基于信号的量化策略模型的泛型框架。它不仅可以&#10;帮助用户构建交易系统，还可以对构建的交易系统进行仿真测试；能够支持对多资产类别和多币种组合进行回测（backtesting）等。&lt;/p&gt;&#10;&lt;p&gt;这个包在设计的过程中充分贯彻了“交易导向型”（Transaction-oriented）原则。&lt;/p&gt;&#10;&lt;p&gt;目前，这个包由Brian G.Peterson在维护，还在开发中，不过已经被很多业内人士拿来实战了。&lt;/p&gt;&#10;&lt;p&gt;因为quantstrat包是一个建立在xts, FinancialInstrument,blotter等包上的高级抽象包，所以，在应用quantstrat包时，&#10;除了除了安装quantstrat包之外，还得记得装上这三个支撑包。看起来安装有点麻烦，正式因为安装麻烦，所以，它才能使得用户用几行简单的代码就能来构建和测试策略。&lt;/p&gt;&#10;&lt;h2 id="quantstrat涉及的量化策略基础知识"&gt;&lt;a href="#quantstrat%e6%b6%89%e5%8f%8a%e7%9a%84%e9%87%8f%e5%8c%96%e7%ad%96%e7%95%a5%e5%9f%ba%e7%a1%80%e7%9f%a5%e8%af%86" class="header-anchor"&gt;&lt;/a&gt;quantstrat涉及的量化策略基础知识&#10;&lt;/h2&gt;&lt;h3 id="基于信号的策略的泛型建模"&gt;&lt;a href="#%e5%9f%ba%e4%ba%8e%e4%bf%a1%e5%8f%b7%e7%9a%84%e7%ad%96%e7%95%a5%e7%9a%84%e6%b3%9b%e5%9e%8b%e5%bb%ba%e6%a8%a1" class="header-anchor"&gt;&lt;/a&gt;基于信号的策略的泛型建模&#10;&lt;/h3&gt;&lt;p&gt;基于信号的策略模型需要先生成交易信号。交易指标是从市场数据中获知的量化指标（包括移动平均、RSI、波动带、通道、动量等）。交易指标应该以矢量化（快速回测）和数据流（实施执行）的形式应用于市场数据，并且假定交易指标是路径独立的（即不受账户、组合类型、现有头寸和交易的限制）。&lt;/p&gt;&#10;&lt;p&gt;交易指标和市场数据的相互作用会生成交易信号（交叉、阈值、倍数），交易信号标示交易者应当采取交易行动的时间，虽然，有时候，你无法行动。跟交易指标类似，交易信号也应该以矢量化和流形式应用于市场数据，并且需要假定交易信号是路径独立的。&lt;/p&gt;&#10;&lt;p&gt;交易规则基于交易指标、交易信号、账户头寸和账户/组合特性生成交易指令。注意关于头寸大小、填补模拟、指令生成和管理的规则与交易指标和交易信号的生成过程是独立的。与交易指标和交易信号不同，交易规则在是执行时是路径依赖式（事实上，也支持非路径依赖式的交易规则，然而，非路径依赖式的交易规则在现实中很少见）的，与已往市场数据和执行规则时的头寸大小相关。交易规则可以生成新的交易指令，也可以对现有交易指令进行修改（比如风险控制、填补、再平衡、介入、退出等）。&lt;/p&gt;&#10;&lt;h3 id="quantstrat如何构建策略"&gt;&lt;a href="#quantstrat%e5%a6%82%e4%bd%95%e6%9e%84%e5%bb%ba%e7%ad%96%e7%95%a5" class="header-anchor"&gt;&lt;/a&gt;Quantstrat如何构建策略？&#10;&lt;/h3&gt;&lt;p&gt;quantstrat通过FinancialInstrument包指定金融工具（包括所用币种）、通过&lt;code&gt;blotter&lt;/code&gt;包跟踪交易信息和市值及组合和账户的变动。&lt;/p&gt;&#10;&lt;p&gt;交易指标通常是跟TTR包中函数类似的标准技术分析函数；交易信号通常有&lt;code&gt;quantstrat&lt;/code&gt;包中的&lt;code&gt;sig*&lt;/code&gt;族函数指定（比如sigComparison、sigCrossover、sigFormula、sigPeak、sigThreshold）；规则通常有quantstrat包中的ruleSignal函数指定。&lt;/p&gt;&#10;&lt;p&gt;用来指定交易指标、交易信号和加以规则的函数不限于上述那些。add.indicator、add.signal、和add.rule的参数为任意R函数。因为支持链是基于xts对象构建的，因此，如果自定义的函数返回结果是xts对象的话，其能够被很好地整合到quantstrat包中。&lt;/p&gt;&#10;&lt;p&gt;策略模型以层形式创建，并且是延迟执行的。这意味着策略可以不加调整地应用于多种不同的组合。执行之前，策略不知道自身将应用到何种金融工具上，也不知道将被传递什么参数。例如，移动平均的时间参数和阈值参数很可能影响策略的性能。参数的默认值可以在策略对象中设定，也可以在执行时通过applyStrategy的参数（参数是一个命名列表，跟参数列表的用法类似）来设定。&lt;/p&gt;&#10;&lt;p&gt;quantstrat对交易指令进行建模，交易指令可能转化为实际交易，也可能不能转化为实际交易。这提供了一个额外功能，可以用来评估策略是如何工作的、为何不工作以及如何改进。例如，策略的性能经常受到“休息现价订单”的改变、替换和删除的影响。订单允许量化策略师检查决策作出时的市场条件。同时，订单历史使得针对许多策略的颇为重要的计算过程变得简单，比如填补比率的计算。&lt;/p&gt;&#10;&lt;h3 id="参数匹配规则"&gt;&lt;a href="#%e5%8f%82%e6%95%b0%e5%8c%b9%e9%85%8d%e8%a7%84%e5%88%99" class="header-anchor"&gt;&lt;/a&gt;参数匹配规则&#10;&lt;/h3&gt;&lt;p&gt;Quantstrat中很多地方会应用到通过策略技术参数传递（参数列表或者…）给交易指标、信号和交易规则函数的变元：&lt;/p&gt;&#10;&lt;p&gt;这些变元按照下面的顺序进行匹配，后面的赋值可以覆盖前值。具体的顺序如下:&#10;赋值给每个交易指标、交易信号和交易规则的arguments=list(…)参数；&#10;调用&lt;code&gt;applyStrategy&lt;/code&gt;是应用的&lt;code&gt;parameters=list{…}&lt;/code&gt;参数；&#10;调用&lt;code&gt;applyStrategy&lt;/code&gt;时，在…中传递的任意附加参数。&lt;/p&gt;&#10;</description></item><item><title>乱码，又见乱码</title><link>https://gewutang.cn/2012/09/13/junk-code-again/</link><pubDate>Thu, 13 Sep 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/09/13/junk-code-again/</guid><description>&lt;p&gt;在Windows系统下，用readHTMLTable函数读取编码为unicod的网页时会出现乱码。这个时候的乱码是因为R是用本地码（通常是GBK）来解释了网页中的unicode，因此出现了符号不兼容。此时，只要用iconv(x,&amp;ldquo;utf-8&amp;rdquo;,&amp;ldquo;gbk&amp;rdquo;)就可以了。然而，有时候会出现另外一种情况：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(XML);&#10;url=&amp;quot;http://data.caixin.com/macro/macro_indicator_more.html?id=F0001&amp;amp;cpage=2&amp;amp;pageSize=30&amp;amp;url=macro_indicator_more.html#top&amp;quot;;&#10;tables=readHTMLTable(url)&#10;head(tables)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;这种情况下icnov好像就无能为力了。不过，事情还是有解决方案的，在readHTMLTable之前加上一句代码就可以了。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;url= htmlParse(url,encoding=&amp;quot;UTF-8&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;看看效果：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(XML)&#10;url &amp;lt;- &amp;quot;http://data.caixin.com/macro/macro_indicator_more.html?id=F0001&amp;amp;cpage=2&amp;amp;pageSize=30&amp;amp;url=macro_indicator_more.html#top&amp;quot;&#10;url&amp;lt;- htmlParse(url,encoding=&amp;quot;UTF-8&amp;quot;)&#10;tables &amp;lt;- readHTMLTable(url)&#10;head(tables)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>获取上市公司主要财务指标</title><link>https://gewutang.cn/2012/09/07/get-financial-data-from-web/</link><pubDate>Fri, 07 Sep 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/09/07/get-financial-data-from-web/</guid><description>&lt;p&gt;写了一段获取上市公司主要财务指标的代码：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 加载XML包&#10;library(XML)&#10;####id:股票代码&#10;####year:年度&#10;get.finance &amp;lt;- function(id,year,...){&#10; web &amp;lt;- paste(&amp;quot;http://money.finance.sina.com.cn/corp/go.php/vFD_FinancialGuideLine/stockid/&amp;quot;,id,&amp;quot;/ctrl/&amp;quot;,year,&amp;quot;/displaytype/4.phtml&amp;quot;,sep=&amp;quot;&amp;quot;)&#10; tables &amp;lt;- readHTMLTable(web)$BalanceSheetNewTable0&#10; colnames(tables)&amp;lt;-tables[1,]&#10; tables &amp;lt;- tables[-1,]&#10; return(tables)&#10;}&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;简单演示一下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(XML)&#10;res &amp;lt;- get.finance(&amp;quot;000002&amp;quot;,&amp;quot;2012&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;基于这些财务数据和价格数据，就可以着手建立股票排名系统了。&lt;/p&gt;&#10;</description></item><item><title>R中的斯皮尔曼等级相关检验与异方差</title><link>https://gewutang.cn/2012/08/16/spearman-test-in-r/</link><pubDate>Thu, 16 Aug 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/08/16/spearman-test-in-r/</guid><description>&lt;p&gt;有一种异方差表现为模型的残差与自变量相关，也就是说，模型残差随着自变量增大而变大或者反之。在这种情况下只要度量模型的残差与自变量的相关性就可以确定是否有异方差了。如果自变量是连续变量，则普通的相关性检验就可以奏效。倘若自变量是年龄、职业、气候等定型变量时就得考虑别的方法了。&lt;/p&gt;&#10;&lt;p&gt;此时，斯皮尔曼等级相关检验是个不错的选择。斯皮尔曼等级相关检验是一种非参数检验方法，它的大致原理是这样的：&lt;/p&gt;&#10;&lt;p&gt;如果变量和变量相关，那么，将两者按照大小排序，则两者的顺序应该是相仿的，若两者相关性弱，则两者的顺序没有明显的一致性。&lt;/p&gt;&#10;&lt;p&gt;举个简单的例子：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; x &amp;lt;-c(25,40,54,58,68)&#10; y &amp;lt;-c(1.6,2.9,10.7,14.8,5.7) &#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;上下对应，下面按照的大小进行排序，则能看到下面的结果：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;rank(x)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4 5&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;rank(y)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 2 4 5 3&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;rank(x)-rank(y)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 0 0 -1 -1 2&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;构造统计量，容易知道等于1时，两者正相关；等于-1时两者负相关。设定原假设统计量为零，该统计量近似服从均值为0，方差为的正态分布，由此可对其进行假设检验。&lt;/p&gt;&#10;&lt;p&gt;R中&lt;code&gt;pspearman&lt;/code&gt;包中的&lt;code&gt;spearman.test&lt;/code&gt;函数可以完成斯皮尔曼等级相关检验：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 安装包，如果未安装&#10;# install.packages(&amp;quot;pspearman&amp;quot;)&#10;library(pspearman)&#10;x=c(25,40,53,58,68)&#10;y=c(1.6,2.9,10.7,14.8,5.7)&#10;spearman.test(x,y)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## &#9;Spearman's rank correlation rho&#10;## &#10;## data: x and y&#10;## S = 6, p-value = 0.2333&#10;## alternative hypothesis: true rho is not equal to 0&#10;## sample estimates:&#10;## rho &#10;## 0.7&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可用&lt;code&gt;cor.test&lt;/code&gt;函数来检验：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;cor.test(x,y,method=&amp;quot;spearman&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## &#9;Spearman's rank correlation rho&#10;## &#10;## data: x and y&#10;## S = 6, p-value = 0.2333&#10;## alternative hypothesis: true rho is not equal to 0&#10;## sample estimates:&#10;## rho &#10;## 0.7&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>棘手的R乱码和给力的iconv函数</title><link>https://gewutang.cn/2012/05/09/iconv-and-r/</link><pubDate>Wed, 09 May 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/05/09/iconv-and-r/</guid><description>&lt;p&gt;从网上抓数据（网页是&lt;code&gt;utf-8&lt;/code&gt;编码）时，发现读入R的数据出现了乱码。代码和返回结果分别如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;library(XML)&#10;id=&amp;quot;000002&amp;quot;&#10;year=&amp;quot;2011&amp;quot;&#10;web=paste(&amp;quot;http://money.finance.sina.com.cn/corp/go.php/vFD_FinancialGuideLine/stockid/&amp;quot;,id,&amp;quot;/ctrl/&amp;quot;,year,&amp;quot;/displaytype/4.phtml&amp;quot;,sep=&amp;quot;&amp;quot;)&#10;web&#10;[1] &amp;quot;http://money.finance.sina.com.cn/corp/go.php/vFD_FinancialGuideLine/stockid/000002/ctrl/2011/displaytype/4.phtml&amp;quot;&#10;tables head(tables)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;涓囩A(000002) 璐一姟镌囨爣 NA&#10;1 鎶ュ憡镞ユ湡 2011-12-31&#10;2 姣忚偂镌囨爣&#10;3 鎽婅杽姣忚偂鏀剁泭(鍏\x83) 1.055&#10;4 锷犳潈姣忚偂鏀剁泭(鍏\x83) 0.88&#10;5 姣忚偂鏀剁泭_璋冩暣鍚\x8e(鍏\x83) 0.88&#10;6 镓ｉ櫎闱炵粡甯告ф崯鐩婂悗镄勬疮镶℃敹鐩\x8a(鍏\x83) 0.87&#10;NA NA NA&#10;1 2011-09-30 2011-06-30 2011-03-31&#10;2&#10;3 0.3735 0.2958 0.1082&#10;4 0.326 0.27 0.11&#10;5 0.326 0.27 0.11&#10;6 0.321 0.27&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;去COS咨询了一番，都说运行完我提供的代码之后没有出现乱码。当时的我有些凌乱。心中苦闷得很，难道R代码的运行结果还跟运行者相关么？如果R语言真能发展到如此智能的地步，我定然乐不可支。当然，这是题外话了，按住不说。&lt;/p&gt;&#10;&lt;p&gt;于是，我泡在论坛上翻了无数旧帖，最终发现了李舰和陈丽云讨论的结果。他们说R中出现乱码后可以用&lt;code&gt;Encoding&lt;/code&gt;来解决。在这个原则指导下我各种&lt;code&gt;Encoding&lt;/code&gt;，却回回都是无功而返。思考再三，我觉得可能是电脑的问题。&lt;/p&gt;&#10;&lt;p&gt;只是电脑的问题那么多，根源在哪儿呢？我贴出了自己的&lt;code&gt;sessionInfo&lt;/code&gt;，想找出问题的根源。幸好有人跟帖也贴出了sessionInfo。对比之下才发现问题出在电脑系统的内部编码上。他们几人所用的都是Linux平台，内部编码设定都是utf。而我苦苦耗在的Windows平台上，系统的内部编码是gbk。&lt;/p&gt;&#10;&lt;p&gt;好了，找到了病根。下一步只要修改一下Windows系统的内部编码就行了。我正欢欣鼓舞呢，颜林林却说，Windows系统没法修改系统编码。好吧!我就像一个病人在熟读各种医书终于发现病根所在之时，却被告知没有药材。绝望之情状如井喷。&lt;/p&gt;&#10;&lt;p&gt;至此，我几近投奔Linux了。结果，无意中见到一个人用iconv函数解决类似的问题。看起来效果不错，我就尝试了一下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;rownames(tables)&amp;lt;-iconv(tables[,1],&amp;quot;UTF-8&amp;quot;,&amp;quot;gbk&amp;quot;)&#10;head(tables[,-1])&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;虽然不知道什么原理，但问题毕竟是解决了。&lt;/p&gt;&#10;</description></item><item><title>R语言在线资源列表</title><link>https://gewutang.cn/2012/02/19/web-resource-about-r/</link><pubDate>Sun, 19 Feb 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/02/19/web-resource-about-r/</guid><description>&lt;p&gt;&lt;a class="link" href="http://alittleknowledge.wordpress.com/2009/09/11/r-for-pedestrians/" target="_blank" rel="noopener"&#10; &gt;http://alittleknowledge.wordpress.com/2009/09/11/r-for-pedestrians/&lt;/a&gt;&#10;&lt;a class="link" href="http://astro.u-strasbg.fr/~fmurtagh/mda-sw/" target="_blank" rel="noopener"&#10; &gt;http://astro.u-strasbg.fr/~fmurtagh/mda-sw/&lt;/a&gt;&#10;&lt;a class="link" href="http://bayes.bgsu.edu/bcwr/" target="_blank" rel="noopener"&#10; &gt;http://bayes.bgsu.edu/bcwr/&lt;/a&gt;&#10;&lt;a class="link" href="http://biocep-distrib.r-forge.r-project.org/doc.html" target="_blank" rel="noopener"&#10; &gt;http://biocep-distrib.r-forge.r-project.org/doc.html&lt;/a&gt;&#10;&lt;a class="link" href="http://biostatistics.iop.kcl.ac.uk/publications/everitt/" target="_blank" rel="noopener"&#10; &gt;http://biostatistics.iop.kcl.ac.uk/publications/everitt/&lt;/a&gt;&#10;&lt;a class="link" href="http://blog.opendatagroup.com/courses/" target="_blank" rel="noopener"&#10; &gt;http://blog.opendatagroup.com/courses/&lt;/a&gt;&#10;&lt;a class="link" href="http://bm2.genes.nig.ac.jp/RGM2/index.php?clear=all" target="_blank" rel="noopener"&#10; &gt;http://bm2.genes.nig.ac.jp/RGM2/index.php?clear=all&lt;/a&gt;&#10;&lt;a class="link" href="http://cm.bell-labs.com/cm/ms/departments/sia/project/trellis/" target="_blank" rel="noopener"&#10; &gt;http://cm.bell-labs.com/cm/ms/departments/sia/project/trellis/&lt;/a&gt;&#10;&lt;a class="link" href="http://code.google.com/p/batchfiles/" target="_blank" rel="noopener"&#10; &gt;http://code.google.com/p/batchfiles/&lt;/a&gt;&#10;&lt;a class="link" href="http://commons.wikimedia.org/wiki/Category:Created_with_R" target="_blank" rel="noopener"&#10; &gt;http://commons.wikimedia.org/wiki/Category:Created_with_R&lt;/a&gt;&#10;&lt;a class="link" href="http://csde.washington.edu/statnet/" target="_blank" rel="noopener"&#10; &gt;http://csde.washington.edu/statnet/&lt;/a&gt;&#10;&lt;a class="link" href="http://dataspora.com/blog/predictive-analytics-using-r/" target="_blank" rel="noopener"&#10; &gt;http://dataspora.com/blog/predictive-analytics-using-r/&lt;/a&gt;&#10;&lt;a class="link" href="http://ecology.msu.montana.edu/labdsv/R/" target="_blank" rel="noopener"&#10; &gt;http://ecology.msu.montana.edu/labdsv/R/&lt;/a&gt;&#10;&lt;a class="link" href="http://ess.r-project.org/" target="_blank" rel="noopener"&#10; &gt;http://ess.r-project.org/&lt;/a&gt;&#10;&lt;a class="link" href="http://factominer.free.fr/" target="_blank" rel="noopener"&#10; &gt;http://factominer.free.fr/&lt;/a&gt;&#10;&lt;a class="link" href="http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/R_BioCondManual.htm" target="_blank" rel="noopener"&#10; &gt;http://faculty.ucr.edu/~tgirke/Documents/R_BioCond/R_BioCondManual.htm&lt;/a&gt;l&#10;&lt;a class="link" href="http://faculty.washington.edu/tlumley/Rcourse/" target="_blank" rel="noopener"&#10; &gt;http://faculty.washington.edu/tlumley/Rcourse/&lt;/a&gt;&#10;&lt;a class="link" href="http://gking.harvard.edu/readme/" target="_blank" rel="noopener"&#10; &gt;http://gking.harvard.edu/readme/&lt;/a&gt;&#10;&lt;a class="link" href="http://grass.itc.it/statsgrass/grass_geostats.html" target="_blank" rel="noopener"&#10; &gt;http://grass.itc.it/statsgrass/grass_geostats.html&lt;/a&gt;&#10;&lt;a class="link" href="http://greg.weebly.com/1/post/2008/10/programming-in-r-makes-serious-statistics-serious-fun.html" target="_blank" rel="noopener"&#10; &gt;http://greg.weebly.com/1/post/2008/10/programming-in-r-makes-serious-statistics-serious-fun.html&lt;/a&gt;&#10;&lt;a class="link" href="http://igraph.sourceforge.net/documentation.html" target="_blank" rel="noopener"&#10; &gt;http://igraph.sourceforge.net/documentation.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.inside-r.org/" target="_blank" rel="noopener"&#10; &gt;http://www.inside-r.org/&lt;/a&gt;&#10;&lt;a class="link" href="http://jblevins.org/computing/r/" target="_blank" rel="noopener"&#10; &gt;http://jblevins.org/computing/r/&lt;/a&gt;&#10;&lt;a class="link" href="http://jgr.markushelbig.org/JGR.html" target="_blank" rel="noopener"&#10; &gt;http://jgr.markushelbig.org/JGR.html&lt;/a&gt;&#10;&lt;a class="link" href="http://learnr.wordpress.com/" target="_blank" rel="noopener"&#10; &gt;http://learnr.wordpress.com/&lt;/a&gt;&#10;&lt;a class="link" href="http://lethain.com/" target="_blank" rel="noopener"&#10; &gt;http://lethain.com/&lt;/a&gt;&#10;&lt;a class="link" href="http://math.acadiau.ca/ACMMaC/Rmpi/examples.html" target="_blank" rel="noopener"&#10; &gt;http://math.acadiau.ca/ACMMaC/Rmpi/examples.html&lt;/a&gt;&#10;&lt;a class="link" href="http://mathesaurus.sourceforge.net/" target="_blank" rel="noopener"&#10; &gt;http://mathesaurus.sourceforge.net/&lt;/a&gt;&#10;&lt;a class="link" href="http://mathstat.helsinki.fi/openbugs/" target="_blank" rel="noopener"&#10; &gt;http://mathstat.helsinki.fi/openbugs/&lt;/a&gt;&#10;&lt;a class="link" href="http://mccammon.ucsd.edu/~bgrant/bio3d/index.html" target="_blank" rel="noopener"&#10; &gt;http://mccammon.ucsd.edu/~bgrant/bio3d/index.html&lt;/a&gt;&#10;&lt;a class="link" href="http://people.biology.ufl.edu/bolker/emdbook/" target="_blank" rel="noopener"&#10; &gt;http://people.biology.ufl.edu/bolker/emdbook/&lt;/a&gt;&#10;&lt;a class="link" href="http://personality-project.org/r/" target="_blank" rel="noopener"&#10; &gt;http://personality-project.org/r/&lt;/a&gt;&#10;&lt;a class="link" href="http://pj.freefaculty.org/R/Rtips.html" target="_blank" rel="noopener"&#10; &gt;http://pj.freefaculty.org/R/Rtips.html&lt;/a&gt;&#10;&lt;a class="link" href="http://pj.freefaculty.org/R/statsRus.html" target="_blank" rel="noopener"&#10; &gt;http://pj.freefaculty.org/R/statsRus.html&lt;/a&gt;&#10;&lt;a class="link" href="http://planatscher.net/svmtut/svmtut.html" target="_blank" rel="noopener"&#10; &gt;http://planatscher.net/svmtut/svmtut.html&lt;/a&gt;&#10;&lt;a class="link" href="http://processtrends.com/Learn_R_Toolkit.htm" target="_blank" rel="noopener"&#10; &gt;http://processtrends.com/Learn_R_Toolkit.htm&lt;/a&gt;&#10;&lt;a class="link" href="http://rocr.bioinf.mpi-sb.mpg.de/" target="_blank" rel="noopener"&#10; &gt;http://rocr.bioinf.mpi-sb.mpg.de/&lt;/a&gt;&#10;&lt;a class="link" href="http://rosuda.org/JRI/" target="_blank" rel="noopener"&#10; &gt;http://rosuda.org/JRI/&lt;/a&gt;&#10;&lt;a class="link" href="http://rpy.sourceforge.net/" target="_blank" rel="noopener"&#10; &gt;http://rpy.sourceforge.net/&lt;/a&gt;&#10;&lt;a class="link" href="http://ryouready.wordpress.com/2009/03/16/r-monitor-function-progress-with-a-progress-bar/" target="_blank" rel="noopener"&#10; &gt;http://ryouready.wordpress.com/2009/03/16/r-monitor-function-progress-with-a-progress-bar/&lt;/a&gt;&#10;&lt;a class="link" href="http://socserv.mcmaster.ca/jfox/" target="_blank" rel="noopener"&#10; &gt;http://socserv.mcmaster.ca/jfox/&lt;/a&gt;&#10;&lt;a class="link" href="http://socserv.socsci.mcmaster.ca/jfox/Courses/R-course/index.html" target="_blank" rel="noopener"&#10; &gt;http://socserv.socsci.mcmaster.ca/jfox/Courses/R-course/index.html&lt;/a&gt;&#10;&lt;a class="link" href="http://stats.math.uni-augsburg.de/Mondrian/" target="_blank" rel="noopener"&#10; &gt;http://stats.math.uni-augsburg.de/Mondrian/&lt;/a&gt;&#10;&lt;a class="link" href="http://tables2graphs.com/doku.php" target="_blank" rel="noopener"&#10; &gt;http://tables2graphs.com/doku.php&lt;/a&gt;&#10;&lt;a class="link" href="http://tolstoy.newcastle.edu.au/R/" target="_blank" rel="noopener"&#10; &gt;http://tolstoy.newcastle.edu.au/R/&lt;/a&gt;&#10;&lt;a class="link" href="http://users.fmg.uva.nl/rgrasman/rpages/2005/09/error-bars-in-plots.html" target="_blank" rel="noopener"&#10; &gt;http://users.fmg.uva.nl/rgrasman/rpages/2005/09/error-bars-in-plots.html&lt;/a&gt;&#10;&lt;a class="link" href="http://wiener.math.csi.cuny.edu/Statistics/R/simpleR/" target="_blank" rel="noopener"&#10; &gt;http://wiener.math.csi.cuny.edu/Statistics/R/simpleR/&lt;/a&gt;&#10;&lt;a class="link" href="http://wiki.math.yorku.ca/index.php/R:_Getting_started" target="_blank" rel="noopener"&#10; &gt;http://wiki.math.yorku.ca/index.php/R:_Getting_started&lt;/a&gt;&#10;&lt;a class="link" href="http://wiki.services.openoffice.org/wiki/R_and_Calc" target="_blank" rel="noopener"&#10; &gt;http://wiki.services.openoffice.org/wiki/R_and_Calc&lt;/a&gt;&#10;&lt;a class="link" href="http://wiki.stdout.org/rcookbook/" target="_blank" rel="noopener"&#10; &gt;http://wiki.stdout.org/rcookbook/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.agr.kuleuven.ac.be/vakken/statisticsbyR/index.htm" target="_blank" rel="noopener"&#10; &gt;http://www.agr.kuleuven.ac.be/vakken/statisticsbyR/index.htm&lt;/a&gt;&#10;&lt;a class="link" href="http://www.ai.rug.nl/~hedderik/R/US2004/" target="_blank" rel="noopener"&#10; &gt;http://www.ai.rug.nl/~hedderik/R/US2004/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.ats.ucla.edu/stat/R/" target="_blank" rel="noopener"&#10; &gt;http://www.ats.ucla.edu/stat/R/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.bioconductor.org/" target="_blank" rel="noopener"&#10; &gt;http://www.bioconductor.org/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.burns-stat.com/" target="_blank" rel="noopener"&#10; &gt;http://www.burns-stat.com/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.cerebralmastication.com/r-resources/" target="_blank" rel="noopener"&#10; &gt;http://www.cerebralmastication.com/r-resources/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.ci.tuwien.ac.at/gR/" target="_blank" rel="noopener"&#10; &gt;http://www.ci.tuwien.ac.at/gR/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.cl.cam.ac.uk/~sjm217/projects/graphics/" target="_blank" rel="noopener"&#10; &gt;http://www.cl.cam.ac.uk/~sjm217/projects/graphics/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.cyclismo.org/tutorial/R/" target="_blank" rel="noopener"&#10; &gt;http://www.cyclismo.org/tutorial/R/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.daimi.au.dk/~besen/TBiB2007/lecture-notes/rpy.html" target="_blank" rel="noopener"&#10; &gt;http://www.daimi.au.dk/~besen/TBiB2007/lecture-notes/rpy.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.decisionsciencenews.com/?p=261" target="_blank" rel="noopener"&#10; &gt;http://www.decisionsciencenews.com/?p=261&lt;/a&gt;&#10;&lt;a class="link" href="http://www.decisionsciencenews.com/?p=264" target="_blank" rel="noopener"&#10; &gt;http://www.decisionsciencenews.com/?p=264&lt;/a&gt;&#10;&lt;a class="link" href="http://www.drewconway.com/zia/?p=1221" target="_blank" rel="noopener"&#10; &gt;http://www.drewconway.com/zia/?p=1221&lt;/a&gt;&#10;&lt;a class="link" href="http://www.econ.uiuc.edu/~econ472/e-Tutorial.html" target="_blank" rel="noopener"&#10; &gt;http://www.econ.uiuc.edu/~econ472/e-Tutorial.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.faculty.ucr.edu/~tgirke/Documents/R_BioCond/R_Programming.html" target="_blank" rel="noopener"&#10; &gt;http://www.faculty.ucr.edu/~tgirke/Documents/R_BioCond/R_Programming.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.harding.edu/fmccown/R/" target="_blank" rel="noopener"&#10; &gt;http://www.harding.edu/fmccown/R/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.ibm.com/developerworks/linux/library/l-r1/" target="_blank" rel="noopener"&#10; &gt;http://www.ibm.com/developerworks/linux/library/l-r1/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.johndcook.com/R_language_for_programmers.html" target="_blank" rel="noopener"&#10; &gt;http://www.johndcook.com/R_language_for_programmers.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.liaad.up.pt/~ltorgo/DataMiningWithR/" target="_blank" rel="noopener"&#10; &gt;http://www.liaad.up.pt/~ltorgo/DataMiningWithR/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.math.montana.edu/Rweb/Rnotes/R.html" target="_blank" rel="noopener"&#10; &gt;http://www.math.montana.edu/Rweb/Rnotes/R.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.math.umass.edu/~lavine/Book/book.html" target="_blank" rel="noopener"&#10; &gt;http://www.math.umass.edu/~lavine/Book/book.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.math.yorku.ca/SCS/Gallery/" target="_blank" rel="noopener"&#10; &gt;http://www.math.yorku.ca/SCS/Gallery/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.maths.bath.ac.uk/~jjf23/book/" target="_blank" rel="noopener"&#10; &gt;http://www.maths.bath.ac.uk/~jjf23/book/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.mayin.org/ajayshah/KB/R/" target="_blank" rel="noopener"&#10; &gt;http://www.mayin.org/ajayshah/KB/R/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.nettakeaway.com/tp/?s=R" target="_blank" rel="noopener"&#10; &gt;http://www.nettakeaway.com/tp/?s=R&lt;/a&gt;&#10;&lt;a class="link" href="http://www.nickfieller.staff.shef.ac.uk/sheff-only/statmod.html" target="_blank" rel="noopener"&#10; &gt;http://www.nickfieller.staff.shef.ac.uk/sheff-only/statmod.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.nytimes.com/2009/01/07/technology/business-computing/07program.html?_r=1" target="_blank" rel="noopener"&#10; &gt;http://www.nytimes.com/2009/01/07/technology/business-computing/07program.html?_r=1&lt;/a&gt;&#10;&lt;a class="link" href="http://www.omegahat.org" target="_blank" rel="noopener"&#10; &gt;http://www.omegahat.org&lt;/a&gt;&#10;&lt;a class="link" href="http://www.personality-project.org/r/" target="_blank" rel="noopener"&#10; &gt;http://www.personality-project.org/r/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.personality-project.org/r/r.anova.html" target="_blank" rel="noopener"&#10; &gt;http://www.personality-project.org/r/r.anova.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.phaget4.org/R/image_matrix.html" target="_blank" rel="noopener"&#10; &gt;http://www.phaget4.org/R/image_matrix.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.phaget4.org/R/R_notes.html" target="_blank" rel="noopener"&#10; &gt;http://www.phaget4.org/R/R_notes.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.psych.upenn.edu/~baron/rpsych/rpsych.html" target="_blank" rel="noopener"&#10; &gt;http://www.psych.upenn.edu/~baron/rpsych/rpsych.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.r-bloggers.com/" target="_blank" rel="noopener"&#10; &gt;http://www.r-bloggers.com/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.rdatamining.com/" target="_blank" rel="noopener"&#10; &gt;http://www.r-cookbook.com/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.rdatamining.com/" target="_blank" rel="noopener"&#10; &gt;http://www.rdatamining.com/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.revolution-computing.com/" target="_blank" rel="noopener"&#10; &gt;http://www.revolution-computing.com/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.rosuda.org/iplots/" target="_blank" rel="noopener"&#10; &gt;http://www.rosuda.org/iplots/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.rparallel.org/examples.php" target="_blank" rel="noopener"&#10; &gt;http://www.rparallel.org/examples.php&lt;/a&gt;&#10;&lt;a class="link" href="http://www.santafe.edu/~aaronc/powerlaws/" target="_blank" rel="noopener"&#10; &gt;http://www.santafe.edu/~aaronc/powerlaws/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.splusbook.com/Rintro/RCourseMaterial.html" target="_blank" rel="noopener"&#10; &gt;http://www.sfu.ca/~sblay/R/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.splusbook.com/Rintro/RCourseMaterial.html" target="_blank" rel="noopener"&#10; &gt;http://www.splusbook.com/Rintro/RCourseMaterial.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.auckland.ac.nz/~paul/RGraphics/rgraphics.html" target="_blank" rel="noopener"&#10; &gt;http://www.stat.auckland.ac.nz/~paul/RGraphics/rgraphics.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.columbia.edu/~gelman/bugsR/" target="_blank" rel="noopener"&#10; &gt;http://www.stat.columbia.edu/~gelman/bugsR/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.pitt.edu/stoffer/tsa2/" target="_blank" rel="noopener"&#10; &gt;http://www.stat.pitt.edu/stoffer/tsa2/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.tamu.edu/~ljin/Finance/stat689-R.htm" target="_blank" rel="noopener"&#10; &gt;http://www.stat.tamu.edu/~ljin/Finance/stat689-R.htm&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.ucl.ac.be/ISdidactique/Rhelp/" target="_blank" rel="noopener"&#10; &gt;http://www.stat.ucl.ac.be/ISdidactique/Rhelp/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.ufl.edu/~aa/cda/cda.html" target="_blank" rel="noopener"&#10; &gt;http://www.stat.ufl.edu/~aa/cda/cda.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.umn.edu/alr/R.html" target="_blank" rel="noopener"&#10; &gt;http://www.stat.umn.edu/alr/R.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.umn.edu/geyer/5102/examp/reg.html#predplot" target="_blank" rel="noopener"&#10; &gt;http://www.stat.umn.edu/geyer/5102/examp/reg.html#predplot&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stat.wisc.edu/~deepayan/SIBS2005/demos/trellis-graphics.html" target="_blank" rel="noopener"&#10; &gt;http://www.stat.wisc.edu/~deepayan/SIBS2005/demos/trellis-graphics.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.statistik.lmu.de/~leisch/Sweave/" target="_blank" rel="noopener"&#10; &gt;http://www.statistik.lmu.de/~leisch/Sweave/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.statmethods.net/index.html" target="_blank" rel="noopener"&#10; &gt;http://www.statmethods.net/index.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.stats.ox.ac.uk/pub/MASS4/" target="_blank" rel="noopener"&#10; &gt;http://www.stats.ox.ac.uk/pub/MASS4/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.statslab.cam.ac.uk/~pat/" target="_blank" rel="noopener"&#10; &gt;http://www.statslab.cam.ac.uk/~pat/&lt;/a&gt;&#10;&lt;a class="link" href="http://www.student.uit.no/~felsted/rtips/rtips_html/rtips.html" target="_blank" rel="noopener"&#10; &gt;http://www.student.uit.no/~felsted/rtips/rtips_html/rtips.html&lt;/a&gt;&#10;&lt;a class="link" href="http://www.theresearchkitchen.com/blog/archives/category/project-euler" target="_blank" rel="noopener"&#10; &gt;http://www.theresearchkitchen.com/blog/archives/category/project-euler&lt;/a&gt;&#10;&lt;a class="link" href="http://www.togaware.com/" target="_blank" rel="noopener"&#10; &gt;http://www.togaware.com/&lt;/a&gt;&#10;&lt;a class="link" href="http://www1.maths.lth.se/help/R/RCC/" target="_blank" rel="noopener"&#10; &gt;http://www1.maths.lth.se/help/R/RCC/&lt;/a&gt;&#10;[http://www2.warwick.ac.uk/fac/sci/moac/degrees/modules/ch923/r_introduction/histograms_etc/ http://wwwmaths.anu.edu.au/~johnm/](&lt;a class="link" href="http://www2.warwick.ac.uk/fac/sci/moac/degrees/modules/ch923/r_introduction/histograms_etc/" target="_blank" rel="noopener"&#10; &gt;http://www2.warwick.ac.uk/fac/sci/moac/degrees/modules/ch923/r_introduction/histograms_etc/&lt;/a&gt; &lt;a class="link" href="http://wwwmaths.anu.edu.au/~johnm/" target="_blank" rel="noopener"&#10; &gt;http://wwwmaths.anu.edu.au/~johnm/&lt;/a&gt;)&#10;&lt;a class="link" href="http://www-stat.stanford.edu/~jhf/R-MART.html" target="_blank" rel="noopener"&#10; &gt;http://www-stat.stanford.edu/~jhf/R-MART.html&lt;/a&gt;&#10;&lt;a class="link" href="http://xweb.geos.ed.ac.uk/~hcp/r_notes/r_notes.html" target="_blank" rel="noopener"&#10; &gt;http://xweb.geos.ed.ac.uk/~hcp/r_notes/r_notes.html&lt;/a&gt;&#10;&lt;a class="link" href="http://zoonek.free.fr/blosxom/R/2006-08-27_The_Grammar_of_Graphics.html" target="_blank" rel="noopener"&#10; &gt;http://zoonek.free.fr/blosxom/R/2006-08-27_The_Grammar_of_Graphics.html&lt;/a&gt;&#10;&lt;a class="link" href="http://zoonek2.free.fr/UNIX/48_R/all.html" target="_blank" rel="noopener"&#10; &gt;http://zoonek2.free.fr/UNIX/48_R/all.html&lt;/a&gt;&lt;/p&gt;&#10;</description></item><item><title>R是一种生活，数据是一种态度</title><link>https://gewutang.cn/2012/02/08/r-is-a-kind-of-life-and-data-is-an-attitude/</link><pubDate>Wed, 08 Feb 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/02/08/r-is-a-kind-of-life-and-data-is-an-attitude/</guid><description>&lt;p&gt;有多少人听说过R软件？有多少人用过R软件？你现在最常用的软件是什么？SAS？SPSS？EViews?如果你是一个经常和数据分析打交道的人，或者从事金融建模，数学建模的人员，还不用R，你就有点out了。如果现在不学R，五年后你没有任何优势可言；如果5年后，你还不学R，那你差不多就可以被淘汰了。&lt;/p&gt;&#10;&lt;p&gt;接下来，我先介绍一下R软件，然后，会详细的讲解为什么你不用R就会out。&lt;/p&gt;&#10;&lt;p&gt;R是有Ross Ihaka跟Robert一起开发的一个面向对象的编程语言。什么是面向对象呢？就像现在，我在这里演讲，直接看见你们，你们就是我面向的对象，当然，这是开玩笑。面向对象的意思就是，R里面的一切东西都是视为对象（Object）。无论是数据框、列表还是函数或者环境，这里先不讲，免得把大家吓跑了。&lt;/p&gt;&#10;&lt;p&gt;R语言的前身是S语言，这个语言一度是数据分析领域里面的标准语言。当然，现在也是，但是正在逐步被R语言取代。S语言是由贝尔实验室开发的，贝尔实验室开发了很多经典的东西，S是其中之一。S语言的缺点是它不是免费的，而R最大的优点在于R是免费的。&lt;/p&gt;&#10;&lt;p&gt;现在很多人用SPSS，SAS,MatLab，但是用的都是盗版软件。从法律上来讲这是非法的，但是非法的东西在中国很流行，很多教授也用这些非法软件，并且还帮着同学去获取盗版软件，其实，这不太可取。当然，在感情上我予以充分理解。&lt;/p&gt;&#10;&lt;p&gt;上次去上海参加第4届R会议，来了一个嘉宾是新西兰人，新西兰是R的故乡，中间熊熹提到她复印了一本ggplot2的书，被外国人看到，外国人就问她征求过版权问题吗？在外国人看来这是很严肃的事情。当然，这是题外话。&lt;/p&gt;&#10;&lt;p&gt;免费是R很大的优点，但不是唯一的。R的最大优点是出色的作图功能、丰富的统计学方法以及超快的更新速度。下面讲一下R的各种功能。&lt;/p&gt;&#10;&lt;p&gt;首先，R可以作为计算器使用，例如（屏幕演示）。其次，出色的绘图功能，例如（屏幕演示，直方图，小提琴图），还可以绘制一些高级的图形，向日葵图，玫瑰花瓣图，脸谱图。当然，这是最基本的功能。虽然很基本，SPSS这些软件是不可能做到这么完美的。R的画图分四个层级，最基本的就是刚才演示的。高级一点的是grid，然后是，Lattice，Lattice的图形是这样的（屏幕演示），很适合做多元数据展示。grid是这样的（屏幕演示），grid图形引入了图层概念，并且可以切换图形的视角。举个例子：（A4纸演示），接下来是ggpolt2：ggplot2是一个更具有创新性的绘图设备，它创建了自己的语法，相当于R里面有创建了一门新的绘图语言。ggplot2的功能是这样的（屏幕演示）。最后，比较终极的绘图BOSS是ggobi，这是一个动态的绘图软件，交互性很强，不过可能很快要被谢益辉的cecran给取代了。后者是前者的加强版。&lt;/p&gt;&#10;&lt;p&gt;然后，就是R建模。R的建模能力超强。建立线性模型，只需要用lm函数就可以了，广义线性模型glm就可以了，广义可加模型gam就可以了。&lt;/p&gt;&#10;&lt;p&gt;然后是，时间序列分析。这个很有用的。我觉得，对于本科生也好，研究生也好，想基于一元或者多元回归做一个比较上层次的论文是困难的。但是，用时间序列分析是可以的，可以用arima，说到这里很多人就笑了，arima这个我知道，终于听到一个自己知道的模型了，其次是garch模型。我知道很多人做garch模型用EViews，但是这个软件太老了，极其不智能，稍微高级的方法都用不了。加一个外生变量要折腾半天。而且最重要的是你用的是盗版软件，话说过来，即使是正版的Eviews也不智能。R里面做garch模型就很简单，用rgarch包就可以了，可以构建各种高级的garch模型，tgarch，igarch，gjrgarch之类的，还有高级的Dccgarch，可能你又听不懂了，还有更高阶的BEKK模型，BEKK没什么神秘的，其实就是多元GARCH模型，就是把GARCH模型从一维推广到了二维了。还有更高阶的，因为参数估计起来太麻烦，所以应用比较少。&lt;/p&gt;&#10;&lt;p&gt;Rgarch包还能计算VaR。也就是Value at Risk。风险价值。这个东西很高级，没有听过吧？其实，我认为上了大三的人就应该很熟悉VaR。但是很多人不知道，因为中国的教育不太成功，我们叫不成功，不叫失败，免得打击教育部。高校的老师，怎么说呢，比较善于推己及人。他们当年读大三的时候，就不懂得VaR，他们复习半年，考上研究生的时候也不怎么懂。所以他们认为别的本科生也不懂，或者说没有能力懂。他们对中国的学生太没有信心了。其实，VaR的概念并不是很难。（演示）&lt;/p&gt;&#10;&lt;p&gt;这就是VaR，其实就是分位数。分位数其实就是对密度函数求变上限的积分，求变上限的积分都会吧？不过，也不用手动求，用R就可以了。&lt;/p&gt;&#10;&lt;p&gt;理论上讲，只要知道了密度函数，求积分不在话下。所以求密度函数其实是VaR的核心。根据求VaR密度函数的方法的不同，可以将它分成三种重用的方法，历史模拟法，蒙特卡洛模拟法，方差-协方差法。历史模拟法就是用历史数据的密度函数代替未来的密度函数，蒙特卡洛模拟法就是假设一个分布，模拟一批随机数。说到随机数，想起来本科期间一件事情，当时精算专业要生成随机数，一批学生不知道怎么做，在Excel里面瞎折腾。我就想不明白，为什么不用R呢，产生正态分布的随机数rnorm(5)就可以了，产生5万个，rnorm(50000)，在Excel里面，折腾死你。&lt;/p&gt;&#10;&lt;p&gt;蒙特卡洛模拟完随机数，就根据这一批样本来计算VaR。方差-协方差呢，跟这个不同，它求的是条件密度函数，理论上讲应该更准确。历史模拟法对历史区间的选择很敏感；蒙特卡洛对分布的假设很敏感，正态分布假设和t分布假设结果相差很大；方差-协方差对厚尾与否很敏感。&lt;/p&gt;&#10;&lt;p&gt;如果是单个资产的话，像上面这样求分位数就搞定了。资产组合的时候，要知道联合分布，才能求分位数。联合分布怎么求，最新的方法是Copula。简单而言就是个复合函数：假设你有联合分布函数F(x1,x2,x3,…)，有边际分布，f(x1),f(x2),f(x3)…要找到要个函数H（·）使得F(x1,x2,x3,…)=H（f(x1),f(x2),f(x2)…）。&lt;/p&gt;&#10;&lt;p&gt;这个函数就是Copula。这是工作原理，操作起来有一系列复杂的技术。当然，求解这个过程计算机会帮忙的，不需要手算。君子善假于物也。&lt;/p&gt;&#10;&lt;p&gt;本科生的时候做过一个项目是关于VaR的。当时学校的一个老师提出过质疑，因为VaR的最初定义是是关于头寸的。而R里面是基于收益率的。两者在测量风险方面没什么差异。但是，他非得坚持算头寸。答辩的时候，我跟他讲这是很容易换算的，他问怎么容易。我就解释给他，当时年少无知，连续向他发问，我估计他很久没有看最新的VaR文献了，因此，我质疑的问题，他一个都答不上来，后面听答辩的同学，开始欢呼，掌声雷动。我很了解同龄人，大家都喜欢看见权威被打倒。这是潜在的暴力倾向，我很不喜欢。值得注意的是，刘姝威老师也在下面拍手。&lt;/p&gt;&#10;&lt;p&gt;现在想起来当时太冲动了，事后我试图向那个老师道歉。当然，不是因为我用错了方法，只是因为我用错了态度。我觉得一个人还是应该尊重另一个人的。&lt;/p&gt;&#10;&lt;p&gt;刘姝威老师后来说，本科生能做出来这个VaR是很不容易的。我当时心里很舒服，得到了赞赏。后来想想，这个赞赏的代价很大。VaR明明很容易计算，她却因为这个儿称赞我，那不是在贬低其他所有的不会算VaR的同学吗？这是我后来想明白的。&lt;/p&gt;&#10;&lt;p&gt;R还能做极值理论。今年上海交大的一个研究生问我用R作极值理论的东西，我就帮他说了一下，他说帮了他大忙。说要感谢我，我说不用，在论文后面，鸣谢一下就可以了。其实，我心里一直在怀疑，研究生要毕业了，极值理论都还不懂，研究生到底读的是神马？更进一步，这样的人为什么能踏过研究生的门槛，问什么能考上研究生呢？中国的研究生录取机制有问题。&lt;/p&gt;&#10;&lt;p&gt;再之外，R在数据挖掘领域是顶呱呱的。里面有各种方法，比如随机森林，支持向量机，Lasso等。什么是Lasso，也许你说，那是lasso，我跟你说，你说错了，这个单词的重音在第二个。关于这方面，刘思喆是专家，你们可以到论坛上或者微博上咨询他。&lt;/p&gt;&#10;&lt;p&gt;R能做的东西很多。那有没有R不能做到的事情？让我想一想，好像还真有。比如，R好像不能下电影，看电影，听音乐。不过，R里面却是提供了很多高级的工具，它提供了一个hook，可以启动电脑中的其他程序，比如迅雷，可以自动下载网页附件，自动解压缩，读入数据等等。很多R粉丝甚至用R关机，用R发微博，发校内状态。R能给人很多惊喜，比如用R下五子棋，扫雷，玩儿递归汉诺塔。做贺卡，马赛克图，这里面是什么知道吗？是AV女优，不信你看看，是不是发现了很多熟人？&lt;/p&gt;&#10;&lt;p&gt;话说回来，很长一段时间里。SPSS,SAS,Matlab还会继续存在，不会骤然消失。我甚至认为这些软件不会消失。因为他还是有自己的受众的。你不能要求所有人的都学习R编程。&lt;/p&gt;&#10;&lt;p&gt;这些软件也有些优点，我最喜欢Matlab，他跟R有点像。好吧R跟matlab有点像，免得伤害Matlab user的感情。曾经有一个人发了一段代码，让用R实现。我不知道那人是什么动机。是想看看R能不能做到，还是想看看COS有没有人会。很不好意思，我两者都会一点，于是我就用R重现了那个过程，代码极其简单。后来，那人说，太牛了，这都能做到。其实，我想说，这不算什么。真的。牛人都在做更重要的事情。&lt;/p&gt;&#10;&lt;p&gt;我希望将来随着时日推移、随着SPSS，SAS，Matlab这一批老人家的辞世，R能快速的成长起来，老人家不愿意学编程，这一点我是很理解的，但是，他们阻碍了R的崛起，R将来势必是一种潮流。&lt;/p&gt;&#10;&lt;p&gt;目前，市场上流行一个观点。即数据越便宜，数据分析技术越昂贵。我早就意识到了这个问题，目前中国获取数据很难，大家都把数据当资源来买。国外就是不一样，国外开放很多数据，因为国外认为，数据里面的信息才是资源。我把数据源放开，你有本事就从里面寻找信息吧。所以，国外分析数据的人就很贵。&lt;/p&gt;&#10;&lt;p&gt;将来，中国的数据提供商肯定会转型，会开始搞咨询，搞分析，而不是单纯的卖数据。卖数据没有前途。他们不卖数据了，数据分析师就会开始值钱了。这一天，我相信很快就到来了。&lt;/p&gt;&#10;&lt;p&gt;R这么好，如何学习R呢?我推荐一些材料给大家。一个是Rforbeginner，R导论。看完之后，看一下Rin a Nutshell，接着看The R book或者Statistics with R。这些资源基本都是开放的。&lt;/p&gt;&#10;&lt;p&gt;你们也可以跟着学校的老师学，如果有用R的老师的话，实在不行就靠自己自学，来论坛问也是可以的。&lt;/p&gt;&#10;&lt;p&gt;总之，R是一片广阔的海域，你认为自己有理想，就放马过来吧。加入时代的浪潮，Come on!最后一点希望，希望在做的各位，将来毕业时都能够写出一篇漂亮的论文，不要抄袭！&lt;/p&gt;&#10;&lt;p&gt;祝各位身体健康，天天快乐，谢谢！&lt;/p&gt;&#10;</description></item><item><title>quantmod:R中的金融分析包（学习笔记）</title><link>https://gewutang.cn/2012/02/06/notes-on-quantmod-2/</link><pubDate>Mon, 06 Feb 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/02/06/notes-on-quantmod-2/</guid><description>&lt;p&gt;很久之前随手写了一份quantmod学习笔记，本来只是随手涂鸦，后来竟然出乎意料地广泛流传。因为那个册子格式混乱，结构也没有筹划，因此一直想着重新写一份。目前还没写完，但已经大致可以看了，先发出来，共需要的人来看，也便于大家提些意见。&lt;/p&gt;&#10;&lt;p&gt;下载：&lt;a class="link" href="https://github.com/dengyishuo/Notes/tree/master/quantmod" target="_blank" rel="noopener"&#10; &gt;notes on quantmod&lt;/a&gt;。&lt;/p&gt;&#10;</description></item><item><title>weibo数据开发思路</title><link>https://gewutang.cn/2012/02/01/thoughts-on-weibo/</link><pubDate>Wed, 01 Feb 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/02/01/thoughts-on-weibo/</guid><description>&lt;p&gt;weibo开放了API提供了众多的接口。只是这些接口对于非开发人员而言过于复杂，不利于weibo数据的开发和挖掘。&lt;/p&gt;&#10;&lt;p&gt;李舰结合weibo的API以及TwitteR包编写了一个叫Rweibo的包，然而Rweibo包的使用方法也相当繁琐。根据自己的需要，我整理了一下weibo数据的开发思路，需要建立的是这样一套东西：&lt;/p&gt;&#10;&lt;p&gt;应当具有的功能：&lt;/p&gt;&#10;&lt;p&gt;1.获取用户A在时间t至时间t+k之间发布的所有微博正文文本内容。&lt;/p&gt;&#10;&lt;p&gt;对应的函数为：weibotext(A,from=t,to=t+k)。&lt;/p&gt;&#10;&lt;p&gt;该函数有三个参数：分别表示用户ID、起始时间t和截止时间t+k。&lt;/p&gt;&#10;&lt;p&gt;2.获取用户A发布的某条微博W的被转发次数和被评论次数。&lt;/p&gt;&#10;&lt;p&gt;3.获取用户A当前的粉丝数量。&lt;/p&gt;&#10;&lt;p&gt;4.获取用户A当前关注的用户数量。&lt;/p&gt;&#10;</description></item><item><title>R语言书籍的学习路线图</title><link>https://gewutang.cn/2012/01/19/how-to-learn-r-by-reading-books/</link><pubDate>Thu, 19 Jan 2012 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2012/01/19/how-to-learn-r-by-reading-books/</guid><description>&lt;p&gt;现在对R感兴趣的人越来越多，很多人都想快速地掌握R。然而，由于目前大部分高校都没有开设R课程，这就导致很多人不知道如何着手学习R。&lt;/p&gt;&#10;&lt;p&gt;对于初学R，最常见的方式是看看百度上的简介。遇到不会的地方，就跑到论坛上吼一嗓子，然后欣欣然（得到解答）或者悲伤（未得到解答）地离去。一直到遇到下一个问题再回来。当然，这不是最好的学习方式。最好的方式是看书。&lt;/p&gt;&#10;&lt;p&gt;目前，市面上介绍R语言的书籍已经很多，中英文都有。那么，众多书籍中，一个菜鸟应该从哪一本入门呢？入门之后如何才能把自己练就成某个方面的高手呢？相信这是很多人心中的疑问。有这种疑问的人有福了，因为笔者将根据自己的经历总结一下R书籍的学习路线图以使大家少走些弯路。&lt;/p&gt;&#10;&lt;p&gt;本文分为6个部分，分别介绍初级入门、高级入门、绘图与可视化、计量经济学、时间序列分析和金融等。&lt;/p&gt;&#10;&lt;h4 id="1初级入门"&gt;&lt;a href="#1%e5%88%9d%e7%ba%a7%e5%85%a5%e9%97%a8" class="header-anchor"&gt;&lt;/a&gt;1.初级入门&#10;&lt;/h4&gt;&lt;p&gt;&lt;a class="link" href="http://cran.r-project.org/doc/manuals/R-intro.pdf" target="_blank" rel="noopener"&#10; &gt;《An Introduction to R》&lt;/a&gt;，这是R官网公布的入门小册子，其有中文版，由丁国徽翻译的，译名是&lt;a class="link" href="http://cran.r-project.org/doc/contrib/Ding-R-intro_cn.pdf" target="_blank" rel="noopener"&#10; &gt;《R导论》&lt;/a&gt;。&lt;a class="link" href="http://cran.r-project.org/doc/contrib/Paradis-rdebuts_en.pdf" target="_blank" rel="noopener"&#10; &gt;《R4Beginners》&lt;/a&gt;，这本小册子有中文版应该叫&lt;a class="link" href="http://www.biosino.org/R/R-doc/files/R4beg_cn_2.0.pdf" target="_blank" rel="noopener"&#10; &gt;《R入门》&lt;/a&gt;。除此之外，还可以去读&lt;a class="link" href="http://www.bjt.name/" target="_blank" rel="noopener"&#10; &gt;刘思喆&lt;/a&gt;的&lt;a class="link" href="http://cos.name/cn/topic/7673" target="_blank" rel="noopener"&#10; &gt;《153分钟学会R》&lt;/a&gt;，对R有一个感性的认识，这个册子收集了R初学者提问频率最高的153个问题。为什么叫153分钟呢？因为最初作者写了153个问题，阅读一个问题花费1分钟时间，全局下来也就是153分钟了。有了这些基础之后，要去读一些经典书籍比较全面的入门书籍，比如《统计建模与R软件》，国外还有《R Cookbook》和《R in action》（中文翻译为《R实战》）等。&lt;/p&gt;&#10;&lt;p&gt;最后隆重推荐《R in a Nutshell》，直译是“果壳里面的R”。当然，这是开玩笑的，”in a Nutshell“是英文俚语，意思是“简单的说”。很多技术类书籍都有Nutshell版本，这类书籍一般翻译为”**核心技术手册“，目前，我们已经译好这本书的中文版，预计今年会面世。这本书很不错，深度和广度都超越同类书籍，大家可以从现在开始期待，并广而告知一下！&lt;/p&gt;&#10;&lt;h4 id="2高级入门"&gt;&lt;a href="#2%e9%ab%98%e7%ba%a7%e5%85%a5%e9%97%a8" class="header-anchor"&gt;&lt;/a&gt;2.高级入门&#10;&lt;/h4&gt;&lt;p&gt;读了上述书籍之后，你就可以去高级入门阶段了。这时候要读的书有两本很经典的。《Statistics with R》和《The R book》以及《Modern Statistics with S》。之所以说这三本书高级，是因为这三本书已经不再限于R了，而是结合了数据分析的各种常见方法来写就的，比较系统的介绍了R在线性回归、方差分析、多元统计、R绘图、时间序列分析、数据挖掘等各方面的内容。看完之后你会发现，哇，原来R能做的事情这么多，而且做起来是那么简洁。&lt;/p&gt;&#10;&lt;p&gt;读到这里已经差不多了，剩下的估计就是你要专门攻读的某个方面内容了。下面大致说一说。&lt;/p&gt;&#10;&lt;h4 id="3绘图与可视化"&gt;&lt;a href="#3%e7%bb%98%e5%9b%be%e4%b8%8e%e5%8f%af%e8%a7%86%e5%8c%96" class="header-anchor"&gt;&lt;/a&gt;3.绘图与可视化&#10;&lt;/h4&gt;&lt;p&gt;亚里斯多德说，“较其他感觉而言，人类更喜欢观看”。因此，绘图和可视化得到很多人的关注和重视。那么，如何学习R画图和数据可视化呢？再简单些，如何画直方图？如何往直方图上添加密度曲线呢？我想读完下面这几本书你就大致会明白了。&lt;/p&gt;&#10;&lt;p&gt;首先，画图入门可以读《R Graphics》，个人认为这本是比较经典的，全面介绍了R中绘图系统。该书对应的有一个网站，google之就可以了。更深入的可以读《Lattice：Multivariate Data Visualization with R》，Lattice是R中针对多元数据可视化而开发的一套绘图系统。上面这些都是比较普通的。对应的有比较文艺和优雅的ggplot2系统，看《ggplot2：Elegant Graphics for Data Analysis》，中文版是《ggplot2:数据分析与图形艺术》。这本书理论性较强，实战比较弱。与之互补的要推荐《The R Graphics cookbook》，中文对应的是《R图形可视化手册》，译者是邓一硕、魏太云和肖楠，这本书详细列举了所有常见数据分析图形的绘制方法，适合做工具书。再有就是交互式图形的书了，著名的交互系统是ggobi，这个我已经喜欢多年，关于ggobi的书有《Interactive and Dynamic Graphics for Data Analysis With R and GGobi》，不过，也只是适宜入门，更多更全面的还是去ggobi的主页吧，上面有各种资料以及包的更新信息。&lt;/p&gt;&#10;&lt;p&gt;此外，R还推出了shiny和rChart以及rechart等包，可以将图形绘制到网页上，这个可以说是未来的主流，不得不关注。&lt;/p&gt;&#10;&lt;p&gt;特别推荐一下，中文版绘图书籍中谢益辉的《现代统计图形》和我们翻译的《R图形可视化手册》。&lt;/p&gt;&#10;&lt;h4 id="4计量经济学"&gt;&lt;a href="#4%e8%ae%a1%e9%87%8f%e7%bb%8f%e6%b5%8e%e5%ad%a6" class="header-anchor"&gt;&lt;/a&gt;4.计量经济学&#10;&lt;/h4&gt;&lt;p&gt;关于计量经济学，首先推荐一本很薄的小册子:《Econometrics In R》，做入门用。然后，是《Applied Econometrics with R》，该书对应的R包是AER包，可以安装之后配合使用，效果甚佳。计量经济学中很大一部分是关于时间序列分析的，这一块内容在下面的地方说。&lt;/p&gt;&#10;&lt;h4 id="5时间序列分析"&gt;&lt;a href="#5%e6%97%b6%e9%97%b4%e5%ba%8f%e5%88%97%e5%88%86%e6%9e%90" class="header-anchor"&gt;&lt;/a&gt;5.时间序列分析&#10;&lt;/h4&gt;&lt;p&gt;时间序列书籍的书籍分两类，一种是比较普适的书籍，典型的代表是：《Time Series Analysis and Its Applications ：with R examples》。该书介绍了各种时间序列分析的经典方法及实现各种经典方法的R代码，该书有中文版。如果不想买的话，建议去作者主页直接下载，英文版读起来很简单。时间序列分析中有一大块儿是关于金融时间序列分析的。这方面比较流行的书有两本《Analysis of financial time series》，这本书的最初是用的S-plus代码，不过新版已经以R代码为主了。这本书适合有时间序列分析基础和金融基础的人来看，因为书中关于时间序列分析的理论以及各种金融知识讲解的不是特别清楚，将极值理论计算VaR的部分就比较难看懂。另外一个比较有意思的是Rmetrics推出的《TimeSeries FAQ》，这本书是金融时间序列入门的东西，讲的很基础，但是很难懂。对应的中文版有《金融时间序列分析常见问题集》。经济领域的时间序列有一种特殊的情况叫协整，很多人很关注这方面的理论，关心这个的可以看《Analysis of Integrated and Cointegrated Time Series with R》。最后，比较高级的一本书是关于小波分析的，看《Wavelet Methods in Statistics with R》。附加一点，关于时间序列聚类的书籍目前比较少见，是一个处女地，有志之士可以开垦。&lt;/p&gt;&#10;&lt;h4 id="6金融"&gt;&lt;a href="#6%e9%87%91%e8%9e%8d" class="header-anchor"&gt;&lt;/a&gt;6.金融&#10;&lt;/h4&gt;&lt;p&gt;金融的领域很广泛，如果是大金融的话，保险也要被纳入此间。用R做金融更多地需要掌握的是金融知识，只会数据分析技术意义寥寥。我觉得这些书对于懂金融、不同数据分析技术的人比较有用，只懂数据分析技术而不动金融知识的人看起来肯定如雾里看花，甚至有人会觉得金融分析比较低级。这方面比较经典的书籍有：《Advanced Topics in Analysis of Economic and Financial Data Using R》以及《Modelling Financial Time Series With S-plus》。金融产品定价之类的常常要用到随机微分方程，有一本叫《Simulation Inference Stochastic Differential Equations：with R examples》的书是关于这方面的内容的，有实例，内容详实。此外，风险度量与管理类比较经典的有《Simulation Techniques in Financial Risk Management》、《Modern Actuarial Risk Theory Using R》和《Quantitative Risk Management：Concepts, Techniques and Tools》。投资组合分析类和期权定价类可以分别看《Portfolio Optimization with R》和《Option Pricing and Estimation of Financial Models with R》。&lt;/p&gt;&#10;&lt;h4 id="7数据挖掘"&gt;&lt;a href="#7%e6%95%b0%e6%8d%ae%e6%8c%96%e6%8e%98" class="header-anchor"&gt;&lt;/a&gt;7.数据挖掘&#10;&lt;/h4&gt;&lt;p&gt;这方面的书有《Data Mining with R:learing with case studies》，《Machine learning for hacks》以及不过《Data Mining with Rattle and R》，书中主要讲了基于Rattle包进行数据挖掘的操作方法，这本书是罕有的全流程数据挖掘工具书，书中详细讲解了从导入数据、清洗数据、数据重整、数据可视化、模型构建、变量选择、模型评价等各个数据挖掘环节，是学习数据挖掘的不二之选。当然，个人比较喜欢Rattle，这本书对应的中文版是《Rattle:R中的数据挖掘GUI》，是由邓一硕、郝智恒、谭丽等翻译的。除了Rattle，Rweka做数据挖掘也很棒。R中数据挖掘方面的包已经足够多了，参考包中的帮助文档就足够了。&lt;/p&gt;&#10;</description></item><item><title>R数据分析实例</title><link>https://gewutang.cn/2011/12/23/r-data-analysis-examples/</link><pubDate>Fri, 23 Dec 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/12/23/r-data-analysis-examples/</guid><description>&lt;h2 id="回归模型regression-models"&gt;&lt;a href="#%e5%9b%9e%e5%bd%92%e6%a8%a1%e5%9e%8bregression-models" class="header-anchor"&gt;&lt;/a&gt;回归模型（Regression Models）&#10;&lt;/h2&gt;&lt;ul&gt;&#10;&lt;li&gt;一元回归&lt;/li&gt;&#10;&lt;li&gt;多元回归&lt;/li&gt;&#10;&lt;li&gt;非线性回归&lt;/li&gt;&#10;&lt;li&gt;稳健回归&lt;/li&gt;&#10;&lt;li&gt;岭回归&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="二分变量及分类模型models-for-binary-and-categorical-outcomes"&gt;&lt;a href="#%e4%ba%8c%e5%88%86%e5%8f%98%e9%87%8f%e5%8f%8a%e5%88%86%e7%b1%bb%e6%a8%a1%e5%9e%8bmodels-for-binary-and-categorical-outcomes" class="header-anchor"&gt;&lt;/a&gt;二分变量及分类模型（Models for Binary and Categorical Outcomes）&#10;&lt;/h2&gt;&lt;ul&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;Logistic回归（Logistic Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;确切Logistic回归（Exact Logistic Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;多分类Logistic回归（Multinomial Logistic Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;顺序Logistic回归（Ordinal Logistic Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;Probit回归（Probit Regression)&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="计数模型count-models"&gt;&lt;a href="#%e8%ae%a1%e6%95%b0%e6%a8%a1%e5%9e%8bcount-models" class="header-anchor"&gt;&lt;/a&gt;计数模型（Count Models）&#10;&lt;/h2&gt;&lt;ul&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;泊松回归（Poisson Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;负二项式回归（Negative Binomial Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;零膨胀泊松回归（Zero-inflated Poisson Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;零膨胀负二项式回归（Zero-inflated Negative Binomial Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;零截断泊松回归（Zero-truncated Poisson）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;零截断负二项式回归（Zero-truncated Negative Binomial)&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="双侧截断回归censored-and-truncated-regression"&gt;&lt;a href="#%e5%8f%8c%e4%be%a7%e6%88%aa%e6%96%ad%e5%9b%9e%e5%bd%92censored-and-truncated-regression" class="header-anchor"&gt;&lt;/a&gt;双侧截断回归（Censored and Truncated Regression）&#10;&lt;/h2&gt;&lt;ul&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;Tobit回归（Tobit Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;截断回归（Truncated Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;区间回归（Interval Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="多因素分析multivariate-analysis"&gt;&lt;a href="#%e5%a4%9a%e5%9b%a0%e7%b4%a0%e5%88%86%e6%9e%90multivariate-analysis" class="header-anchor"&gt;&lt;/a&gt;多因素分析（Multivariate Analysis）&#10;&lt;/h2&gt;&lt;ul&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;单边多元方差分析（One-way MANOVA）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;判别函数分析（Discriminant Function Analysis）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;典型相关分析（Canonical Correlation Analysis）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;多元回归分析（Multivariate Multiple Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="效能样本量分析power-analysis--sample-size"&gt;&lt;a href="#%e6%95%88%e8%83%bd%e6%a0%b7%e6%9c%ac%e9%87%8f%e5%88%86%e6%9e%90power-analysis--sample-size" class="header-anchor"&gt;&lt;/a&gt;效能/样本量分析（Power Analysis / Sample Size）&#10;&lt;/h2&gt;&lt;ul&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;单样本t检验（Single-sample t-test）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;配对样本t检验（Paired-sample t-test）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;独立样本t检验（Independent-sample t-test）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;独立比例分析(Two Independent Proportions)&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;单侧方差分析（One-way ANOVA）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;多元回归（Multiple Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;参数精度分析（Accuracy in Parameter Estimation）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;Logistic回归（Logistic Regression）&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="其它"&gt;&lt;a href="#%e5%85%b6%e5%ae%83" class="header-anchor"&gt;&lt;/a&gt;其它&#10;&lt;/h2&gt;&lt;ul&gt;&#10;&lt;li&gt;潜类分析（Latent Class Analysis）&lt;/li&gt;&#10;&lt;/ul&gt;&#10;</description></item><item><title>从股票代码到公司名</title><link>https://gewutang.cn/2011/12/12/from-symbol-to-company-name/</link><pubDate>Mon, 12 Dec 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/12/12/from-symbol-to-company-name/</guid><description>&lt;p&gt;Ruser也有Ruser的恶习，经常弄的什么事情都想用R来完成：用R玩儿扫雷、用R玩汉诺塔、用R玩儿黑白棋、用R获取股票数据、用R获取财务数据。&lt;/p&gt;&#10;&lt;p&gt;现在想的是，如果已经知道一个股票代码，比如上交所的000061，如何知道其对应的公司名称呢？如果能找到一个数据库，其包含公司名称、公司股票代码、公司简称就可以完成这样的事情了。&lt;/p&gt;&#10;&lt;p&gt;最典型的金融数据库有什么呢？google?yahoo? yahoo是可以的。代码：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(quantmod)&#10;paste(getQuote(&amp;quot;000061.ss&amp;quot;, what=yahooQF(&amp;quot;Name&amp;quot;))[,2])&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;返回结果如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;[1] &amp;quot;SSE CORPORATE BON&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>R数据分析实例：稳健回归</title><link>https://gewutang.cn/2011/12/09/r-data-analysis-examples-robust-regression/</link><pubDate>Fri, 09 Dec 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/12/09/r-data-analysis-examples-robust-regression/</guid><description>&lt;p&gt;**按语：**当数据含有离群点（Outliar）或者强影响点（influential observation）时，稳健回归（Robust Regression）会比普通最小二乘法(OLS)的表现要更优异。稳健回归也可以用来检测数据中的强影响点。&lt;/p&gt;&#10;&lt;p&gt;&lt;strong&gt;提示:&lt;/strong&gt; 本文旨在介绍与稳健回归相关的R命令，因此，并未全面覆盖稳健回归的相关知识，也不涉及数据清洗、数据检测、模型假设和模型诊断等内容。&lt;/p&gt;&#10;&lt;p&gt;文档内容基于R 2.14.0，最后更新于2011年12月19日。&lt;/p&gt;&#10;&lt;h4 id="简介"&gt;&lt;a href="#%e7%ae%80%e4%bb%8b" class="header-anchor"&gt;&lt;/a&gt;简介&#10;&lt;/h4&gt;&lt;p&gt;介绍几个线性回归（linear regression）中的术语：&lt;/p&gt;&#10;&lt;p&gt;&lt;strong&gt;残差（Residual）&lt;/strong&gt;:基于回归方程的预测值与观测值的差。&lt;/p&gt;&#10;&lt;p&gt;&lt;strong&gt;离群点（Outlier）&lt;/strong&gt;:线性回归（linear regression）中的离群点是指对应残差较大的观测值。也就是说，当某个观测值与基于回归方程的预测值相差较大时，该观测值即可视为离群点。 离群点的出现一般是因为样本自身较为特殊或者数据录入错误导致的，当然也可能是其他问题。&lt;/p&gt;&#10;&lt;p&gt;&lt;strong&gt;杠杆率（Leverage）&lt;/strong&gt;: 当某个观测值所对应的预测值为极端值时，该观测值称为高杠杆率点。杠杆率衡量的是独立变量对自身均值的偏异程度。高杠杆率的观测值对于回归方程的参数有重大影响。&lt;/p&gt;&#10;&lt;p&gt;&lt;strong&gt;影响力点：（Influence）&lt;/strong&gt;: 若某观测值的剔除与否，对回归方程的系数估计有显著相应，则该观测值是具有影响力的，称为影响力点。影响力是高杠杆率和离群情况引起的。&lt;/p&gt;&#10;&lt;p&gt;&lt;strong&gt;Cook距离（Cook&amp;rsquo;s distance&lt;/strong&gt;）: 综合了杠杆率信息和残差信息的统计量。&lt;/p&gt;&#10;&lt;p&gt;使用最小二乘回归时，有时候会遇到离群点和高杠杆率点。此时，若认定离群点或者高杠杆率点的出现并非因为数据录入错误或者该该观测值来自另外一个总体的话，使用最小二乘回归会变得很棘手，因为数据分析者因为没有充分的理由剔除离群点和高杠杆率。此时稳健回归是个极佳的替代方案。稳健回归在剔除离群点或者高杠杆率点和保留离群点或高杠杆率点并像最小二乘法那样平等使用各点之间找到了一个折中。其在估计回归参数时，根据观测值的稳健情况对观测值进行赋权。简而言之，稳健回归是加权最小二乘回归，或称文艺最小二乘回归。&lt;/p&gt;&#10;&lt;p&gt;&lt;strong&gt;MASS&lt;/strong&gt; 包中的 &lt;strong&gt;rlm&lt;/strong&gt;命令提供了不同形式的稳健回归拟合方式。接下来，以基于Huber方法和bisquare方法下的M估计为例来进行演示。这是两种最为基本的M估计方法。在M估计中，要做的事情是在满足约束 $ \Sigma_{i=1}^{n}w_{i}(y_i-x_{i}^{&amp;rsquo;}b) x_{i}^{&amp;rsquo;} = 0 $时，求出使得 &lt;code&gt;\(\Sigma w_{i}^2e_i^2\)&lt;/code&gt; 最小的参数。&lt;/p&gt;&#10;&lt;p&gt;由于权重的估计依赖于残差，而残差的估计又反过来依赖于权重，因此需用迭代重复加权最小二乘（ &lt;strong&gt;I&lt;/strong&gt;teratively &lt;strong&gt;R&lt;/strong&gt;eweighted &lt;strong&gt;L&lt;/strong&gt;east &lt;strong&gt;S&lt;/strong&gt;quares ，IRLS）来估计参数。&lt;/p&gt;&#10;&lt;p&gt;举例，第j次迭代得到的系数矩阵为:$ B_j = \left[X^{&amp;rsquo;}W_{j-1}X-1X]-1X^{&amp;rsquo;}W_{j-1}Y\right]$ ，这里下脚标表示求解过程中的迭代次数，而不是通常的行标或者列标，持续这一过程，直到结果收敛为止。Huber方法下，残差较小的观测值被赋予的权重为1，残差较大的观测值的权重随着残差的增大而递减。而bisquare方法下，所有的非0残差所对应观测值的权重都是递减的。&lt;/p&gt;&#10;&lt;p&gt;Huber权重函数通过阈值参数 $ k $ 控制对异常值的敏感度：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;w(e) =&#10;\begin{cases}&#10;1 &amp;amp; \text{若 } |e| \leq k \&#10;\frac{k}{|e|} &amp;amp; \text{若 } |e| &amp;gt; k&#10;\end{cases}&#10;$$&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;Huber方法特性&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;‌&lt;strong&gt;梯度惩罚&lt;/strong&gt;‌：对 &lt;code&gt;\(|e| &amp;gt; k\)&lt;/code&gt; 的残差施加线性惩罚，平衡效率与鲁棒性&lt;/li&gt;&#10;&lt;li&gt;‌&lt;strong&gt;连续性&lt;/strong&gt;‌：权重函数在 $ |e| = k $ 处连续但不可微分&lt;/li&gt;&#10;&lt;li&gt;‌&lt;strong&gt;参数选择&lt;/strong&gt;‌：典型值 $ k = 1.345\sigma $，覆盖约95%的正态分布数据&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;Bisquare权重函数采用平滑的二次递减形式：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;w(e) =&#10;\begin{cases}&#10;\left(1 - \left(\frac{e}{k}\right)^2\right)^2 &amp;amp; \text{若 } |e| \leq k \&#10;0 &amp;amp; \text{若 } |e| &amp;gt; k&#10;\end{cases}&#10;$$&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;Bisquare方法特性&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;‌&lt;strong&gt;硬截断&lt;/strong&gt;‌：完全忽略 &lt;code&gt;\(|e| &amp;gt; k\)&lt;/code&gt; 的观测值&lt;/li&gt;&#10;&lt;li&gt;‌&lt;strong&gt;平滑性&lt;/strong&gt;‌：权重曲线在 $ |e| = k $ 处连续且一阶可导&lt;/li&gt;&#10;&lt;li&gt;‌&lt;strong&gt;参数选择&lt;/strong&gt;‌：典型值 $ k = 4.685\sigma $，保留约99%的正常数据&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h4 id="数据描述"&gt;&lt;a href="#%e6%95%b0%e6%8d%ae%e6%8f%8f%e8%bf%b0" class="header-anchor"&gt;&lt;/a&gt;数据描述&#10;&lt;/h4&gt;&lt;p&gt;下面用到的数据是Alan Agresti和Barbara Finlay所著的《Statistical Methods for Social Sciences》中的crime数据集。&lt;/p&gt;&#10;&lt;p&gt;该数据集的变量分别是：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;州代码(&lt;strong&gt;sid&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;li&gt;州名 (&lt;strong&gt;state&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;li&gt;每十万人暴力犯罪数(&lt;strong&gt;crime&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;li&gt;每十万人谋杀犯罪数 (&lt;strong&gt;murder&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;li&gt;城市圈人口占比 (&lt;strong&gt;pctmetro&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;li&gt;白人占比(&lt;strong&gt;pctwhite&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;li&gt;高中及以上教育占比 (&lt;strong&gt;pcths&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;li&gt;贫困线以下人口占比 (&lt;strong&gt;poverty&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;li&gt;单亲家庭人口占比 (&lt;strong&gt;single&lt;/strong&gt;)&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;pre&gt;&lt;code&gt;&#10;该数据集共有51个观测值。接下来用数据集中的**poverty** 和 **single** 变量来预测 **crime**.&#10;&#10;&#10;``` r&#10;library(foreign)&#10;&#10;cdata &amp;lt;- read.dta(&amp;quot;http://www.ats.ucla.edu/stat/data/crime.dta&amp;quot;)&#10;&#10;summary(cdata)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h4 id="稳健回归"&gt;&lt;a href="#%e7%a8%b3%e5%81%a5%e5%9b%9e%e5%bd%92" class="header-anchor"&gt;&lt;/a&gt;稳健回归&#10;&lt;/h4&gt;&lt;p&gt;先对数据进行OLS回归，重点观察回归结果中的残差、拟合值、Cook距离和杠杆率。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;ols &amp;lt;- lm(crime ~ poverty + single, data = cdata) summary(ols)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;从图上看出，第 9, 第25和第5个观测值可能是离群点，看看这些观测值所属的是哪些州。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;cdata[c(9, 25, 51), 1:2]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;可以猜测，DC、Florida和Mississippi这三个地方所对应的观测值可能具有较大的残差或者杠杆率。&lt;/p&gt;&#10;&lt;p&gt;下面观察一下Cook距离较大的观测值有哪些。在判断Cook距离大小的时候，通常采用过的经验分界点是Cook距离序列的4/n处，其中n是观测值的个数。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(MASS) &#10;d1 &amp;lt;- cooks.distance(ols) &#10;r &amp;lt;- stdres(ols) &#10;a &amp;lt;- cbind(cdata, d1, r) &#10;a[d1 &amp;gt; 4/51, ]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;本来应当先删除DC所对应的观测值，因为DC对应的并不是州。然而，由于DC所对应的Cook距离较大保留DC有助于我们进行观察。下面生成一个&lt;strong&gt;absr1&lt;/strong&gt;变量，其对应的为残差序列的绝对值，取出残差绝对值较大的观测值：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;rabs &amp;lt;- abs(r) a &amp;lt;- cbind(cdata, d1, r, rabs) asorted &amp;lt;- a[order(-rabs), ] asorted[1:10, ]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;现在转向稳健回归。再提示一下，稳健回归是通过迭代重复加权最小二乘来完成的。其对应的R函数是&lt;strong&gt;MASS&lt;/strong&gt;包中的&lt;strong&gt;rlm&lt;/strong&gt;。IRLS对应的有多个权重函数（ weighting functions），首先演示一下Huber方法。&lt;/p&gt;&#10;&lt;p&gt;演示过程中，重点关注IRLS过程得出的权重结果。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;rr.huber &amp;lt;- rlm(crime ~ poverty + single, data = cdata) &#10;summary(rr.huber)&#10;hweights &amp;lt;- data.frame(state = cdata$state, resid = rr.huber$resid, weight = rr.huber$w) &#10;hweights2 &amp;lt;- hweights[order(rr.huber$w), ] hweights2[1:15, ]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;容易看出来，观测值的残差绝对值越大，其被赋予的权重越小。结果表明Mississippi所对应的观测值被赋予的权重是最小的，其次是Florida所对应的观测值，而所有未被展示的观测值的权重皆为1。由于OLS回归中所有观测值的权重都为1，因此，稳健回归中权重为1的观测值越多，则稳健回归于OLS回归的分析结果越相近。&lt;/p&gt;&#10;&lt;p&gt;接下来，用bisquare方法来进行稳健回归过程。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;rr.bisquare &amp;lt;- rlm(crime ~ poverty + single, data=cdata, psi = psi.bisquare) summary(rr.bisquare)&#10;biweights &amp;lt;- data.frame(state = cdata$state, resid = rr.bisquare$resid, weight = rr.bisquare$w) &#10;biweights2 &amp;lt;- biweights[order(rr.bisquare$w), ] &#10;biweights2[1:15, ]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;与Huber方法相比，bisquare方法下的 Mississippi观测值被赋予了极小的权重，并且两种方法估计出的回归参数也相差甚大。通常，当稳健回归跟OLS回归的分析结果相差较大时，数据分析者采用稳健回归较为明智。稳健回归和OLS回归的分析结果的较大差异通常暗示着离群点对模型参数产生了较大影响。所有的方法都有长处和软肋，稳健回归也不例外。稳健回归中，Huber方法的软肋在于无法很好的而处理极端离群点，而bisquare方法的软肋在于回归结果不易收敛，以至于经常有多个最优解。&lt;/p&gt;&#10;&lt;p&gt;除此之外，两种方法得出的参数结果极为不同，尤其是&lt;strong&gt;single&lt;/strong&gt;变量的系数和截距项(&lt;strong&gt;intercept&lt;/strong&gt;)。不过，一般而言无需关注截距项，除非事先已经对预测变量进行了中心化，此时截距项才显的有些用处。再有， 变量** poverty** 的系数在两种方法下都不显著，而变量 &lt;strong&gt;single&lt;/strong&gt;则刚好相反，都较为显著。&lt;/p&gt;&#10;&lt;h4 id="思考"&gt;&lt;a href="#%e6%80%9d%e8%80%83" class="header-anchor"&gt;&lt;/a&gt;思考：&#10;&lt;/h4&gt;&lt;ul&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;稳健回归没有解决OLS回归中的异方差问题，有关这一问题可以参见&lt;strong&gt;sandwich&lt;/strong&gt;包中的 &lt;strong&gt;lm&lt;/strong&gt;函数。&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;这里展示的只是在&lt;strong&gt;R&lt;/strong&gt;实现M估计的一种方法，读者尚可以在&lt;strong&gt;rlm&lt;/strong&gt;中发现更多方法，比如MM等。此外，&lt;strong&gt;robustbase&lt;/strong&gt;包中&lt;strong&gt;ltsReg&lt;/strong&gt;可以用来实现最小截平方（ Least trimmed squares）。&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h4 id="参考资料"&gt;&lt;a href="#%e5%8f%82%e8%80%83%e8%b5%84%e6%96%99" class="header-anchor"&gt;&lt;/a&gt;参考资料：&#10;&lt;/h4&gt;&lt;ul&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;Li, G. 1985. Robust regression. In Exploring Data Tables, Trends and Shapes, ed. D. C. Hoaglin, F. Mosteller, and J. W. Tukey, Wiley.&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;John Fox, Applied regression analysis,linear models and related models, Sage publications, Inc, 1997&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h4 id="更多内容"&gt;&lt;a href="#%e6%9b%b4%e5%a4%9a%e5%86%85%e5%ae%b9" class="header-anchor"&gt;&lt;/a&gt;更多内容：&#10;&lt;/h4&gt;&lt;ul&gt;&#10;&lt;li&gt;&lt;a class="link" href="http://stat.ethz.ch/R-manual/R-patched/library/MASS/html/rlm.html" target="_blank" rel="noopener"&#10; &gt; R documentation for &lt;strong&gt;rlm&lt;/strong&gt;&lt;/a&gt;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;</description></item><item><title>R中的3维HCPC图</title><link>https://gewutang.cn/2011/11/28/3d-graph-of-hcpc-in-r/</link><pubDate>Mon, 28 Nov 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/11/28/3d-graph-of-hcpc-in-r/</guid><description>&lt;p&gt;第四届R会议上，余苓提到了一个叫FactoMineR的包，这个包提供了一个可以绘制立体谱系图的函数plot.HCPC()。我记得之前有人在COS论坛上问过这个问题，我就特别留意了一下这个函数。&lt;/p&gt;&#10;&lt;p&gt;它的用法如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 安装包,如果未安装&#10;# install.packages(&amp;quot;FactoMineR&amp;quot;)&#10;library(FactoMineR) #加载包&#10;data(iris) #加载数据&#10;res.hcpc &amp;lt;- HCPC(iris[1:4], nb.clust=3) #基于PC的聚类&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;&lt;img src="https://gewutang.cn/2011/11/28/3d-graph-of-hcpc-in-r/index_files/figure-html/unnamed-chunk-1-1.png" width="672" /&gt;&lt;img src="https://gewutang.cn/2011/11/28/3d-graph-of-hcpc-in-r/index_files/figure-html/unnamed-chunk-1-2.png" width="672" /&gt;&lt;img src="https://gewutang.cn/2011/11/28/3d-graph-of-hcpc-in-r/index_files/figure-html/unnamed-chunk-1-3.png" width="672" /&gt;&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;plot.HCPC(res.hcpc, choice=&amp;quot;3D.map&amp;quot;, angle=60) #3D谱系图&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/11/28/3d-graph-of-hcpc-in-r/index_files/figure-html/unnamed-chunk-1-4.png" width="672" /&gt;&#10;&lt;p&gt;但是，这个图不够好，因为这个图缺少该有的交互性。等我有时间了，我会用rgl包重新写一个具有交互功能的立体谱系图。&lt;/p&gt;&#10;</description></item><item><title>apply函数族入门</title><link>https://gewutang.cn/2011/11/09/apply-family/</link><pubDate>Wed, 09 Nov 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/11/09/apply-family/</guid><description>&lt;p&gt;在任何一个R语言问答网站或者论坛，你都能看见这样的问题：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &#10; &lt;/blockquote&gt;&#10;&lt;p&gt;Q:如何用循环做【&amp;hellip;各种奇怪的事情&amp;hellip;】&#10;A:不用用循环哦，亲！apply函数可以解决这个问题哦，亲！&lt;/p&gt;&#10;&lt;p&gt;上面答案中提到的这个神奇的apply函数到底是什么？下面通过一些简单的操作示范一下。&lt;/p&gt;&#10;&lt;p&gt;打开R，敲入??apply函数，选定base包部分你会看到下面的东西：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;base::apply Apply Functions Over Array Margins&#10;base::by Apply a Function to a Data Frame Split by Factors&#10;base::eapply Apply a Function Over Values in an Environment&#10;base::lapply Apply a Function over a List or Vector&#10;base::mapply Apply a Function to Multiple List or Vector Arguments&#10;base::rapply Recursively Apply a Function to a List&#10;base::tapply Apply a Function Over a Ragged Array&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;下面一一示范。&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;apply&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;先看看帮助文档中对其的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“Returns a vector or array or list of values obtained by applying a function to margins of an array or matrix. ”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;好吧，vector、array和function是神马我都明白，margins是什么？我来翻译一下吧，margins为1时是指行，margins为2时是指列，如果是c(1:2)，好吧，这个啰嗦的举动，指的是整个array或者matrix。&lt;/p&gt;&#10;&lt;p&gt;例子如下:&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#创建一个10行2列的矩阵&#10;m &amp;lt;- matrix(c(1:10,11:20),nrow=10,ncol=2)&#10;&#10;#求m的每一行的均值&#10;apply(m,1,mean)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 6 7 8 9 10 11 12 13 14 15&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#求m的每一列的均值&#10;apply(m,2,mean)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 5.5 15.5&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#将m的每个值除以2&#10;apply(m,1:2,function(x) x/2)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2]&#10;## [1,] 0.5 5.5&#10;## [2,] 1.0 6.0&#10;## [3,] 1.5 6.5&#10;## [4,] 2.0 7.0&#10;## [5,] 2.5 7.5&#10;## [6,] 3.0 8.0&#10;## [7,] 3.5 8.5&#10;## [8,] 4.0 9.0&#10;## [9,] 4.5 9.5&#10;## [10,] 5.0 10.0&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;最后一个例子仅仅是为了示范，我们有更简单的方法一秒钟实现。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;m/2&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2]&#10;## [1,] 0.5 5.5&#10;## [2,] 1.0 6.0&#10;## [3,] 1.5 6.5&#10;## [4,] 2.0 7.0&#10;## [5,] 2.5 7.5&#10;## [6,] 3.0 8.0&#10;## [7,] 3.5 8.5&#10;## [8,] 4.0 9.0&#10;## [9,] 4.5 9.5&#10;## [10,] 5.0 10.0&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;by&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档中的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &#10; &lt;/blockquote&gt;&#10;&lt;p&gt;“Function by is an object-oriented wrapper for tapply applied to data frames. ”&lt;/p&gt;&#10;&lt;p&gt;事实上，by的功能绝不是这一句话所能描述的。接着读下去，你会看到&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“A data frame is split by row into data frames subsetted by the values of one or more factors, and function FUN is applied to each subset in turn. ”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;这里，我们用一个带有定性变量的数据进行示范。这个数据集就是著名的iris。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;attach(iris)&#10;head(iris)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Sepal.Length Sepal.Width Petal.Length Petal.Width Species&#10;## 1 5.1 3.5 1.4 0.2 setosa&#10;## 2 4.9 3.0 1.4 0.2 setosa&#10;## 3 4.7 3.2 1.3 0.2 setosa&#10;## 4 4.6 3.1 1.5 0.2 setosa&#10;## 5 5.0 3.6 1.4 0.2 setosa&#10;## 6 5.4 3.9 1.7 0.4 setosa&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#根据Species分类，求前4个变量的均值&#10;by(iris[,1:4],Species,mean)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Warning in mean.default(data[x, , drop = FALSE], ...):&#10;## 参数不是数值也不是逻辑值：返回NA&#10;## Warning in mean.default(data[x, , drop = FALSE], ...):&#10;## 参数不是数值也不是逻辑值：返回NA&#10;## Warning in mean.default(data[x, , drop = FALSE], ...):&#10;## 参数不是数值也不是逻辑值：返回NA&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Species: setosa&#10;## [1] NA&#10;## ------------------------------------------------------------ &#10;## Species: versicolor&#10;## [1] NA&#10;## ------------------------------------------------------------ &#10;## Species: virginica&#10;## [1] NA&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;其实，就是根据一个定性变量将数据分为若干个子集，再对各子集进行apply操作。&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;eapply&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“eapply applies FUN to the named values from an environment and returns the results as a list. The user can request that all named objects are used (normally names that begin with a dot are not). The output is not sorted and no enclosing environments are searched. ”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;有理解这句话，重点是理解environment这个东西。environment相当于是R里面的一个小系统，这个系统包含有自己的变量和函数等内容。&lt;/p&gt;&#10;&lt;p&gt;用一个简单的例子来示范：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#创建一个新的environment&#10;e=new.env()&#10;#在e中创建两个变量&#10;e$a=1:10&#10;e$b=11:20&#10;#求e中变量的均值&#10;eapply(e,mean)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $a&#10;## [1] 5.5&#10;## &#10;## $b&#10;## [1] 15.5&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;一般人儿可能不常用environment这个东西。不过，Bioconductor们是例外。&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;lapply&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“lapply returns a list of the same length as X, each element of which is the result of applying FUN to the corresponding element of X. ”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;这是apply函数的帮助文档中最简明扼要的一个。直接给示范：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#创建一个list&#10;l=list(a=1:10,b=11:20)&#10;#计算list中每个元素的均值&#10;lapply(l,mean)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $a&#10;## [1] 5.5&#10;## &#10;## $b&#10;## [1] 15.5&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#计算list中每个元素的和&#10;lapply(l,sum)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $a&#10;## [1] 55&#10;## &#10;## $b&#10;## [1] 155&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;lapply的文档中让我们进一步参考sapply、vapply和replicate。那我们走去看看。&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;sapply&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“sapply is a user-friendly version and wrapper of lapply by default returning a vector, matrix or, if simplify=&amp;ldquo;array&amp;rdquo;, an array if appropriate, by applying simplify2array(). sapply(x, f, simplify=FALSE, USE.NAMES=FALSE) is the same as lapply(x,f). ”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;上面一堆简单说就是，lapply返回的是一个含有两个元素$a和$b的list，而sapply返回的是一个含有元素[[&amp;ldquo;a&amp;rdquo;]]和[[&amp;ldquo;b&amp;rdquo;]]的vector，或者列名为a和b的矩阵。&lt;/p&gt;&#10;&lt;p&gt;示范如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#创建一个list&#10;l=list(a=1:10,b=11:20)&#10;#用sapply求均值&#10;l.mean=sapply(l,mean)&#10;#观察返回结果的类型&#10;class(l.mean)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;numeric&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;l.mean[['a']]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 5.5&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;vapply&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“vapply is similar to sapply, but has a pre-specified type of return value, so it can be safer (and sometimes faster) to use.”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;直接示范：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;l=list(a=1:10,b=11:20)&#10;#用vapply函数计算五分位数&#10;l.fivenum=vapply(l,fivenum,c(Min.=0,&amp;quot;lst Qu.&amp;quot;=0,Median=0,&amp;quot;3rd Qu.&amp;quot;=0,Max.=0))&#10;class(l.fivenum)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;matrix&amp;quot; &amp;quot;array&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#结果&#10;l.fivenum&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## a b&#10;## Min. 1.0 11.0&#10;## lst Qu. 3.0 13.0&#10;## Median 5.5 15.5&#10;## 3rd Qu. 8.0 18.0&#10;## Max. 10.0 20.0&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;从结果可以看到，vapply返回的是一个矩阵。矩阵的列名是list的元素，行名取决于函数的输出结果。&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;replicate&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档的描述:&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“replicate is a wrapper for the common use of sapply for repeated evaluation of an expression (which will usually involve random number generation). ”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;replicate是一个非常强大的函数，它有两个强制参数：replications,即操作的重复次数；function，及要重复的操作。还有一个可选择参数：simplify=T，是否将操作结果转化为vector或者matrix。&lt;/p&gt;&#10;&lt;p&gt;示范：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;replicate(10,rnorm(10))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4] [,5] [,6]&#10;## [1,] 0.09404565 0.6900446 0.20266413 0.5129547 1.0128168 0.05653415&#10;## [2,] -0.91284275 0.4148158 0.52344728 1.6220620 -0.1530737 0.05569266&#10;## [3,] -2.82534108 -0.8308159 -0.80378790 -0.4079487 -2.1890716 -0.63564857&#10;## [4,] -0.88857743 -0.3077837 -1.04967642 0.3230530 0.1094893 0.38889519&#10;## [5,] 0.21849109 1.2910931 -1.31689751 -0.8643641 -1.6985050 -0.72514369&#10;## [6,] 0.42406931 1.0962243 0.03433455 -0.3644647 -1.1519254 -0.51264405&#10;## [7,] -0.95389493 0.8339559 -0.48655834 0.0271446 0.8224275 -0.75322140&#10;## [8,] 1.30411129 0.6961557 -0.94826540 3.8187493 1.9491568 -0.70021472&#10;## [9,] 1.42619896 1.3484791 -1.77604799 0.2154067 0.3761675 -0.24362034&#10;## [10,] -0.12993140 0.2320959 -0.08696657 1.2382602 0.5781700 -1.26176561&#10;## [,7] [,8] [,9] [,10]&#10;## [1,] 0.29583451 1.7547814 -0.4761433 -2.9786950&#10;## [2,] -1.51743386 -2.1529347 0.3729536 0.2775196&#10;## [3,] -0.46015526 -0.7021302 -0.3539648 -0.6730854&#10;## [4,] 0.89778909 0.1765478 1.9319342 0.3784471&#10;## [5,] 1.42831439 -0.3437932 0.3734149 0.3974802&#10;## [6,] 0.07412502 -2.5053443 -1.0342991 0.8934034&#10;## [7,] 0.04454659 -0.1709211 -0.4627233 1.0121957&#10;## [8,] -0.46424059 -0.2812505 -0.3270812 0.2869938&#10;## [9,] 0.11599570 1.5177862 0.2759767 0.8952857&#10;## [10,] 0.59676528 -0.1538958 -0.9503086 -0.3969758&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;mapply&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“mapply is a multivariate version of sapply. mapply applies FUN to the first elements of each &amp;hellip; argument, the second elements, the third elements, and so on. Arguments are recycled if necessary. ”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;如果你认真看看mapply的帮助文档的话，我打赌你会看到头大。这里给看官两个简单的例子：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;l1=list(a=1:10,b=11:20)&#10;l2=list(c=21:30,d=31:40)&#10;l1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $a&#10;## [1] 1 2 3 4 5 6 7 8 9 10&#10;## &#10;## $b&#10;## [1] 11 12 13 14 15 16 17 18 19 20&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;l2&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $c&#10;## [1] 21 22 23 24 25 26 27 28 29 30&#10;## &#10;## $d&#10;## [1] 31 32 33 34 35 36 37 38 39 40&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#计算l1,l2中各元素的和&#10;mapply(sum,l1$a,l1$b,l2$c,l2$d)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 64 68 72 76 80 84 88 92 96 100&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;竖直看下来，加总就得到了上面的结果。&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;rapply&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“rapply is a recursive version of lapply. ”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;这个描述是史上最差描述之一。因为rapply跟recursive并没有太大关系。rapply的创造性在于提供了一个结果输出形式的参数。&lt;/p&gt;&#10;&lt;p&gt;示范：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#创建list&#10;l=list(a=1:10,b=11:20)&#10;#计算l中元素的log2&#10;rapply(l,log2)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## a1 a2 a3 a4 a5 a6 a7 a8 &#10;## 0.000000 1.000000 1.584963 2.000000 2.321928 2.584963 2.807355 3.000000 &#10;## a9 a10 b1 b2 b3 b4 b5 b6 &#10;## 3.169925 3.321928 3.459432 3.584963 3.700440 3.807355 3.906891 4.000000 &#10;## b7 b8 b9 b10 &#10;## 4.087463 4.169925 4.247928 4.321928&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#将结果的输出形式设定为list&#10;&#10;rapply(l,log2,how=&amp;quot;list&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $a&#10;## [1] 0.000000 1.000000 1.584963 2.000000 2.321928 2.584963 2.807355 3.000000&#10;## [9] 3.169925 3.321928&#10;## &#10;## $b&#10;## [1] 3.459432 3.584963 3.700440 3.807355 3.906891 4.000000 4.087463 4.169925&#10;## [9] 4.247928 4.321928&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#计算均值&#10;rapply(l,mean)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## a b &#10;## 5.5 15.5&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;rapply(l,mean,how=&amp;quot;list&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $a&#10;## [1] 5.5&#10;## &#10;## $b&#10;## [1] 15.5&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;综上，rapply函数的输出结果取决于函数和how参数。当how=&amp;ldquo;list&amp;quot;时，数据的原始结构被保留，否则，输出结果被转化为vector。&lt;/p&gt;&#10;&lt;p&gt;当然，看官还可以将classes函数传递给rapply函数。例如在混合型list中，可以通过classes=numeric，是的函数子对数字型元素进行操作。&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;tapply&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;帮助文档的描述：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;“Apply a function to each cell of a ragged array, that is to each (non-empty) group of values given by a unique combination of the levels of certain factors.”&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;语焉不详。翻译一下大概是：&lt;/p&gt;&#10;&lt;p&gt;“tapply(X, INDEX, FUN = NULL, &amp;hellip;, simplify = TRUE)”中的“X”是&#10;“an atomic object, typically a vector.”，而“INDEX”是“list of factors, each of same length as X. The elements are coerced to factors by as.factor.”&lt;/p&gt;&#10;&lt;p&gt;依然以iris数据集为例示范一下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;attach(iris)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following objects are masked from iris (pos = 3):&#10;## &#10;## Petal.Length, Petal.Width, Sepal.Length, Sepal.Width, Species&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#根据sprcies进行分类，计算petal的均值&#10;tapply(iris$Petal.Length,Species,mean)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## setosa versicolor virginica &#10;## 1.462 4.260 5.552&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;简短的总结：&lt;/p&gt;&#10;&lt;p&gt;这里给出的都是极其简单的例子，基于最简单的数据，和最简单的函数。因为对于每一个操作而言，看官都可查看数据的操作前状态和操作后状态，这样便于看官知道，操作到底对数据干了什么事情。&lt;/p&gt;&#10;&lt;p&gt;当然了，apply函数的功能不限于文中介绍的这些，进一步的功用期待看官自己去挖掘。&lt;/p&gt;&#10;&lt;p&gt;给出几个使用apply函数的建议，在使用之前应当思考：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;原始数据是什么类型？vector?matrix?data frame?&amp;hellip;.&lt;/li&gt;&#10;&lt;li&gt;想对原始数据的哪些子集进行操作？行?列？所有元素？&amp;hellip;.&lt;/li&gt;&#10;&lt;li&gt;操作将返回什么结果？原始数据的结构是如何变化的？&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;只是一个老生常谈的关于“输入——操作——输出”的故事：你有什么？你想要什么？两者之间需要什么？&lt;/p&gt;&#10;</description></item><item><title>R与月跨度函数，理论与应用的差距</title><link>https://gewutang.cn/2011/09/15/r-and-time-span-function/</link><pubDate>Thu, 15 Sep 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/09/15/r-and-time-span-function/</guid><description>&lt;p&gt;R在处理数据方面的灵活性一直都被人们赞誉。当然，理论界的人的多些，应用界的人相对较少。&lt;/p&gt;&#10;&lt;p&gt;混迹应用界的人一般会对R有更多的细节要求。比如在处理日期的时候，如果我想获取两个日期，2010年3月25日和2010年6月27日的月跨度，R里面就没有现存的函数。这一点让我意外，因为这是数据处理实务中经常遇到的问题。为什么R包的作者没有想到呢？不要抱怨，抱怨没用，这就是理论和应用的差距。&lt;/p&gt;&#10;&lt;p&gt;应用者的一切以方便为导向，理论者则不同，他们负责提供石头，建筑有时候要靠你自己去完成。&lt;/p&gt;&#10;&lt;p&gt;花了一会儿时间，找到了三个石头，length,months,seq。完成了建筑，在代码里面把2010-03-**全部处理为2010-03-01，把2010-06-**全部处理成2010-06-01。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;d1=&amp;quot;2010-03-25&amp;quot;&#10;d2=&amp;quot;2010-06-24&amp;quot;&#10;&#10;length(seq(from=as.Date(paste(substr(d1,1,7),&amp;quot;01&amp;quot;,sep=&amp;quot;-&amp;quot;)),&#10; to=as.Date(paste(substr(d2,1,7),&amp;quot;01&amp;quot;,sep=&amp;quot;-&amp;quot;)),&#10; by=&amp;quot;month&amp;quot;))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;当然，也可以封装一下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;month.span=function(d1,d2){&#10; date1=paste(substr(d1,1,7),&amp;quot;01&amp;quot;,sep=&amp;quot;-&amp;quot;)&#10; date2=paste(substr(d2,1,7),&amp;quot;01&amp;quot;,sep=&amp;quot;-&amp;quot;)&#10; L=length(seq(from=as.Date(date1),to=as.Date(date2),by=&amp;quot;month&amp;quot;))&#10; L&#10;}&#10;&#10;month.span(d1,d2)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>非线性模型极大似然估计方法</title><link>https://gewutang.cn/2011/09/13/max-likelyho/</link><pubDate>Tue, 13 Sep 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/09/13/max-likelyho/</guid><description>&lt;h2 id="一模型设定与概率框架"&gt;&lt;a href="#%e4%b8%80%e6%a8%a1%e5%9e%8b%e8%ae%be%e5%ae%9a%e4%b8%8e%e6%a6%82%e7%8e%87%e6%a1%86%e6%9e%b6" class="header-anchor"&gt;&lt;/a&gt;一、模型设定与概率框架&#10;&lt;/h2&gt;&lt;p&gt;设非线性生产函数形式为：&#10;$$&#10;y_i = aL_i^bK_i^c + \epsilon_i \quad (i=1,&amp;hellip;,n)&#10;$$&#10;其中误差项 &lt;code&gt;\(\epsilon_i \sim N(0,\sigma^2)\)&lt;/code&gt;，则观测值 &lt;code&gt;\(y_i\)&lt;/code&gt; 服从均值为 &lt;code&gt;\(aL_i^bK_i^c\)&lt;/code&gt;、方差为 &lt;code&gt;\(\sigma^2\)&lt;/code&gt; 的正态分布。&lt;/p&gt;&#10;&lt;h2 id="二似然函数构建"&gt;&lt;a href="#%e4%ba%8c%e4%bc%bc%e7%84%b6%e5%87%bd%e6%95%b0%e6%9e%84%e5%bb%ba" class="header-anchor"&gt;&lt;/a&gt;二、似然函数构建&#10;&lt;/h2&gt;&lt;h3 id="1-联合概率密度函数"&gt;&lt;a href="#1-%e8%81%94%e5%90%88%e6%a6%82%e7%8e%87%e5%af%86%e5%ba%a6%e5%87%bd%e6%95%b0" class="header-anchor"&gt;&lt;/a&gt;1. 联合概率密度函数&#10;&lt;/h3&gt;&lt;p&gt;$$&#10;L(a,b,c,\sigma) = \prod_{i=1}^n \frac{1}{\sqrt{2\pi\sigma^2}} \exp\left[ -\frac{(y_i-aL_i^bK_i^c)^2}{2\sigma^2} \right]&#10;$$&lt;/p&gt;&#10;&lt;h3 id="2-负对数似然函数目标函数"&gt;&lt;a href="#2-%e8%b4%9f%e5%af%b9%e6%95%b0%e4%bc%bc%e7%84%b6%e5%87%bd%e6%95%b0%e7%9b%ae%e6%a0%87%e5%87%bd%e6%95%b0" class="header-anchor"&gt;&lt;/a&gt;2. 负对数似然函数（目标函数）&#10;&lt;/h3&gt;&lt;p&gt;$$&#10;\ell(a,b,c,\sigma) = -\ln L = \frac{n}{2}\ln(2\pi) + n\ln\sigma + \frac{1}{2\sigma^2}\sum_{i=1}^n (y_i - aL_i^bK_i^c)^2&#10;$$&lt;/p&gt;&#10;&lt;h2 id="三参数估计流程"&gt;&lt;a href="#%e4%b8%89%e5%8f%82%e6%95%b0%e4%bc%b0%e8%ae%a1%e6%b5%81%e7%a8%8b" class="header-anchor"&gt;&lt;/a&gt;三、参数估计流程&#10;&lt;/h2&gt;&lt;h3 id="1-数据处理与准备"&gt;&lt;a href="#1-%e6%95%b0%e6%8d%ae%e5%a4%84%e7%90%86%e4%b8%8e%e5%87%86%e5%a4%87" class="header-anchor"&gt;&lt;/a&gt;1. 数据处理与准备&#10;&lt;/h3&gt;&lt;pre&gt;&lt;code class="language-r"&gt;# 导入数据&#10;data &amp;lt;- data.frame(&#10; y = c(76,47,97,107,123,139,159,152,191,201,207,200),&#10; L = c(0.02,0.02,0.06,0.06,0.11,0.11,0.22,0.22,0.56,0.56,1.10,1.10),&#10; K = c(1.1,0.9,2.3,2.1,3.4,3.6,4.5,4.3,5.8,6.0,7.2,7.0)&#10;)&#10;&#10;# 定义负对数似然函数&#10;mloglik &amp;lt;- function(theta) {&#10; a &amp;lt;- theta[1]&#10; b &amp;lt;- theta[2]&#10; c &amp;lt;- theta[3]&#10; sigma &amp;lt;- theta[4]&#10; &#10; y_pred &amp;lt;- a * data$L^b * data$K^c&#10; residuals &amp;lt;- data$y - y_pred&#10; n &amp;lt;- length(data$y)&#10; &#10; # 避免\sigma 趋近于零&#10; if(sigma &amp;lt;= 0) return(1e10)&#10; &#10; (n/2)*log(2*pi) + n*log(sigma) + sum(residuals^2)/(2*sigma^2)&#10;}&#10;&#10;# 采用线性化方法获取初始值&#10;log_model &amp;lt;- lm(log(y) ~ log(L) + log(K), data = data)&#10;theta_init &amp;lt;- c(&#10; exp(coef(log_model)[1]),&#10; coef(log_model)[2],&#10; coef(log_model)[3],&#10; sd(resid(log_model))&#10;)&#10;&#10;# 优化求解&#10;fit &amp;lt;- nlm(mloglik, theta_init, hessian = TRUE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Warning in nlm(mloglik, theta_init, hessian = TRUE): NA/NaN replaced by maximum&#10;## positive value&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Warning in nlm(mloglik, theta_init, hessian = TRUE): Inf replaced by maximum&#10;## positive value&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 提取估计结果&#10;params &amp;lt;- fit$estimate&#10;names(params) &amp;lt;- c(&amp;quot;a&amp;quot;, &amp;quot;b&amp;quot;, &amp;quot;c&amp;quot;, &amp;quot;sigma&amp;quot;)&#10;params&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## a b c sigma &#10;## 55.45620820 -0.02273718 0.67704166 7.67493891&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>NASDAQ有泡沫吗</title><link>https://gewutang.cn/2011/09/06/demo-about-lppl/</link><pubDate>Tue, 06 Sep 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/09/06/demo-about-lppl/</guid><description>&lt;h2 id="lppl模型是什么"&gt;&lt;a href="#lppl%e6%a8%a1%e5%9e%8b%e6%98%af%e4%bb%80%e4%b9%88" class="header-anchor"&gt;&lt;/a&gt;LPPL模型是什么&#10;&lt;/h2&gt;&lt;p&gt;LPPL（对数周期性幂律）模型是由Didier Sornette等学者提出的金融市场泡沫检测模型，用于识别资产价格在崩盘前的非线性加速增长模式。该模型结合了幂律增长和对数周期性振荡，被广泛应用于金融泡沫预警和临界点预测。&lt;/p&gt;&#10;&lt;p&gt;模型的核心是资产价格演化方程：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;\ln p(t) = A + B(t_c - t)^\beta \left[1 + C\cos\left(\omega \ln(t_c - t) + \phi\right)\right]&#10;$$&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;&lt;code&gt;\(t_c\)&lt;/code&gt; 是临界时间（预测的崩盘时间）&lt;/li&gt;&#10;&lt;li&gt;&lt;code&gt;\(\beta\)&lt;/code&gt; 是幂律指数&lt;/li&gt;&#10;&lt;li&gt;&lt;code&gt;\(\omega\)&lt;/code&gt; 是振荡频率（典型值5-15）&lt;/li&gt;&#10;&lt;li&gt;&lt;code&gt;\(C\)&lt;/code&gt; 是振荡幅度&lt;/li&gt;&#10;&lt;li&gt;&lt;code&gt;\(\phi\)&lt;/code&gt; 是相位参数&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;其中： &lt;code&gt;\(0 \lt \beta \lt 1\)&lt;/code&gt;&lt;/p&gt;&#10;&lt;p&gt;LPPL模型具有如下特征：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;价格加速增长&#10;&lt;ul&gt;&#10;&lt;li&gt;幂律项 &lt;code&gt;\((t_c - t)^\beta\)&lt;/code&gt; 描述价格超指数增长。&lt;/li&gt;&#10;&lt;li&gt;典型泡沫阶段 &lt;code&gt;\(\beta \in (0,1)\)&lt;/code&gt;，反映增长速率随时间递增。&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;对数周期振荡&#10;&lt;ul&gt;&#10;&lt;li&gt;其中 &lt;code&gt;\(cos\left[\omega\ln\left(t_{c}-t\right)\right]\)&lt;/code&gt; 反映投资者博弈产生的离散尺度不变性。&lt;/li&gt;&#10;&lt;li&gt;震荡幅度随 &lt;code&gt;\(t\to t_{c}\)&lt;/code&gt; 增大，体现市场分歧加剧。&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;临界时间特性&#10;&lt;ul&gt;&#10;&lt;li&gt;当 &lt;code&gt;\(t\to t_{c}\)&lt;/code&gt; 时模型预测系统失稳。&lt;/li&gt;&#10;&lt;li&gt;实际崩盘可能发生在 &lt;code&gt;\(t_{c}\)&lt;/code&gt; 前6个月内。&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="拟合模型"&gt;&lt;a href="#%e6%8b%9f%e5%90%88%e6%a8%a1%e5%9e%8b" class="header-anchor"&gt;&lt;/a&gt;拟合模型&#10;&lt;/h2&gt;&lt;pre&gt;&lt;code class="language-r"&gt;# 加载依赖包&#10;library(quantmod)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：xts&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：zoo&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## 载入程序包：'zoo'&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following objects are masked from 'package:base':&#10;## &#10;## as.Date, as.Date.numeric&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：TTR&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Registered S3 method overwritten by 'quantmod':&#10;## method from&#10;## as.zoo.data.frame zoo&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(DEoptim)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：parallel&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## DEoptim package&#10;## Differential Evolution algorithm in R&#10;## Authors: D. Ardia, K. Mullen, B. Peterson and J. Ulrich&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(ggplot2)&#10;&#10;# 获取纳斯达克指数数据（2010-01-01至2011-08-30）&#10;getSymbols(&amp;quot;^IXIC&amp;quot;, src = &amp;quot;yahoo&amp;quot;, from = &amp;quot;2010-01-01&amp;quot;, to = &amp;quot;2011-08-30&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;IXIC&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;nasdaq &amp;lt;- data.frame(&#10; t = 1:nrow(IXIC), &#10; ln_p = log(Ad(IXIC))&#10;)&#10;&#10;colnames(nasdaq)=c(&amp;quot;t&amp;quot;,&amp;quot;ln_p&amp;quot;)&#10;# 数据降噪（7日移动平均）&#10;nasdaq$ln_p_smooth &amp;lt;- stats::filter(nasdaq$ln_p, rep(1/7, 7), sides = 2)&#10;nasdaq &amp;lt;- na.omit(nasdaq) # 剔除NA值&#10;&#10;&#10;# 定义LPPL模型函数&#10;lppl_model &amp;lt;- function(params, t) {&#10; A &amp;lt;- params[&amp;quot;A&amp;quot;]; B &amp;lt;- params[&amp;quot;B&amp;quot;]; tc &amp;lt;- params[&amp;quot;tc&amp;quot;]&#10; beta &amp;lt;- params[&amp;quot;beta&amp;quot;]; C &amp;lt;- params[&amp;quot;C&amp;quot;]; omega &amp;lt;- params[&amp;quot;omega&amp;quot;]; phi &amp;lt;- params[&amp;quot;phi&amp;quot;]&#10; term &amp;lt;- pmax(tc - t, 1e-6) # 防止出现负数&#10; A + B * term^beta + C * term^beta * cos(omega * log(term) + phi)&#10;}&#10;&#10;# 定义损失函数（均方误差）&#10;loss &amp;lt;- function(params) {&#10; pred &amp;lt;- lppl_model(params, nasdaq$t)&#10; if (any(is.na(pred))) return(Inf)&#10; mean((pred - nasdaq$ln_p_smooth)^2, na.rm = TRUE)&#10;}&#10;&#10;# 参数约束范围&#10;lower &amp;lt;- c(&#10; A = min(nasdaq$ln_p_smooth), &#10; B = -2, &#10; tc = max(nasdaq$t) + 1, &#10; beta = 0.01, &#10; C = 0, &#10; omega = 6, &#10; phi = 0&#10;)&#10;&#10;upper &amp;lt;- c(&#10; A = max(nasdaq$ln_p_smooth), &#10; B = 0, &#10; tc = max(nasdaq$t) * 1.2, &#10; beta = 0.99, &#10; C = 0.5, &#10; omega = 13, &#10; phi = 2 * pi&#10;)&#10;&#10;&#10;# 全局优化（差分进化算法）&#10;set.seed(123)&#10;de_result &amp;lt;- DEoptim(&#10; fn = loss, &#10; lower = lower, &#10; upper = upper, &#10; control = list(&#10; itermax = 500, &#10; NP = 100, &#10; trace = FALSE&#10; )&#10;)&#10;&#10;# 局部优化（L-BFGS-B）&#10;final_params &amp;lt;- optim(&#10; de_result$optim$bestmem, &#10; fn = loss, &#10; method = &amp;quot;L-BFGS-B&amp;quot;,&#10; lower = lower, &#10; upper = upper&#10;)$par&#10;&#10;# 输出参数估计结果&#10;cat(&amp;quot;LPPL模型参数估计结果：\n&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## LPPL模型参数估计结果：&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;print(round(final_params, 4))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## A B tc beta C omega phi &#10;## 7.9574 -0.0009 459.8781 0.9167 0.0000 7.7609 5.3808&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="结果解读"&gt;&lt;a href="#%e7%bb%93%e6%9e%9c%e8%a7%a3%e8%af%bb" class="header-anchor"&gt;&lt;/a&gt;结果解读&#10;&lt;/h2&gt;&lt;p&gt;从模型结果可以看出：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;临界时间：$t_c$若输出值为&lt;code&gt; round(final_params,4)$tc&lt;/code&gt;，需结合市场背景评估泡沫风险；&lt;/li&gt;&#10;&lt;li&gt;震荡频率：$\omega$介于6-13区间符合典型泡沫特征；&lt;/li&gt;&#10;&lt;li&gt;衰减指数: &lt;code&gt;\(\beta\)&lt;/code&gt; 接近&lt;code&gt; round(final_params,4)$beta&lt;/code&gt;表明价格波动趋于临界点时分歧加大。&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h2 id="模型结果可视化"&gt;&lt;a href="#%e6%a8%a1%e5%9e%8b%e7%bb%93%e6%9e%9c%e5%8f%af%e8%a7%86%e5%8c%96" class="header-anchor"&gt;&lt;/a&gt;模型结果可视化&#10;&lt;/h2&gt;&lt;pre&gt;&lt;code class="language-r"&gt;# 生成预测值&#10;nasdaq$pred &amp;lt;- lppl_model(final_params, nasdaq$t)&#10;&#10;# 绘制拟合曲线&#10;ggplot(nasdaq, aes(x = t)) +&#10; geom_line(aes(y = ln_p, color = &amp;quot;原始对数价格&amp;quot;), alpha = 0.5) +&#10; geom_line(aes(y = ln_p_smooth, color = &amp;quot;平滑序列&amp;quot;), linetype = &amp;quot;dashed&amp;quot;) +&#10; geom_line(aes(y = pred, color = &amp;quot;LPPL拟合&amp;quot;), linewidth = 1) +&#10; scale_color_manual(values = c(&amp;quot;原始对数价格&amp;quot; = &amp;quot;grey&amp;quot;, &amp;quot;平滑序列&amp;quot; = &amp;quot;blue&amp;quot;, &amp;quot;LPPL拟合&amp;quot; = &amp;quot;red&amp;quot;)) +&#10; labs(&#10; title = &amp;quot;纳斯达克指数LPPL模型拟合效果（2020-2025）&amp;quot;,&#10; x = &amp;quot;交易日序数&amp;quot;, &#10; y = &amp;quot;对数价格&amp;quot;&#10; ) +&#10; theme_minimal() +&#10; theme(legend.position = &amp;quot;top&amp;quot;, plot.title = element_text(hjust = 0.5))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/09/06/demo-about-lppl/index_files/figure-html/unnamed-chunk-2-1.png" width="672" /&gt;&#10;</description></item><item><title>R中的魔方矩阵</title><link>https://gewutang.cn/2011/08/29/magic/</link><pubDate>Mon, 29 Aug 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/08/29/magic/</guid><description>&lt;p&gt;某个朋友去证券公司笔试，题目中竟然有一道要求用C语言完成魔方矩阵的输出。如果之前没有做过相关练习，骤然间写出代码可是不容易的事情。&lt;/p&gt;&#10;&lt;p&gt;今天下午查了一下R中的魔方矩阵，发现里面已经有一个magic包可以完成魔方矩阵的输出。R真有点无所不包的气势。&lt;/p&gt;&#10;&lt;h2 id="魔方矩阵原理应用与可视化实现"&gt;&lt;a href="#%e9%ad%94%e6%96%b9%e7%9f%a9%e9%98%b5%e5%8e%9f%e7%90%86%e5%ba%94%e7%94%a8%e4%b8%8e%e5%8f%af%e8%a7%86%e5%8c%96%e5%ae%9e%e7%8e%b0" class="header-anchor"&gt;&lt;/a&gt;魔方矩阵：原理、应用与可视化实现&#10;&lt;/h2&gt;&lt;h3 id="一数学原理"&gt;&lt;a href="#%e4%b8%80%e6%95%b0%e5%ad%a6%e5%8e%9f%e7%90%86" class="header-anchor"&gt;&lt;/a&gt;一、数学原理&#10;&lt;/h3&gt;&lt;p&gt;魔方矩阵（Magic Square）又称幻方，是$n \times n$的方阵，满足以下特性：&lt;/p&gt;&#10;&lt;ol&gt;&#10;&lt;li&gt;&lt;strong&gt;等和定律&lt;/strong&gt;：每行、每列及两条主对角线的元素和相等，称为魔方常数$M =\frac{n(n^2+1)}{2}$；&lt;/li&gt;&#10;&lt;li&gt;&lt;strong&gt;元素排列&lt;/strong&gt;：包含$1$到$n^2$的连续自然数；&lt;/li&gt;&#10;&lt;li&gt;&lt;strong&gt;构造规律&lt;/strong&gt;：奇数阶常用Siamese方法（楼梯法），偶数阶采用LUX或边界填充策略。&lt;/li&gt;&#10;&lt;/ol&gt;&#10;&lt;p&gt;以3阶魔方为例：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;&lt;code&gt;\begin{bmatrix} 8 &amp;amp; 1 &amp;amp; 6 \\ 3 &amp;amp; 5 &amp;amp; 7 \\ 4 &amp;amp; 9 &amp;amp; 2 \\ \end{bmatrix}&lt;/code&gt;&#10;$$&lt;/p&gt;&#10;&lt;p&gt;其行、列、对角线之和均为$15$。&lt;/p&gt;&#10;&lt;h3 id="二核心价值"&gt;&lt;a href="#%e4%ba%8c%e6%a0%b8%e5%bf%83%e4%bb%b7%e5%80%bc" class="header-anchor"&gt;&lt;/a&gt;二、核心价值&#10;&lt;/h3&gt;&lt;h4 id="1-科学研究维度"&gt;&lt;a href="#1-%e7%a7%91%e5%ad%a6%e7%a0%94%e7%a9%b6%e7%bb%b4%e5%ba%a6" class="header-anchor"&gt;&lt;/a&gt;1. 科学研究维度&#10;&lt;/h4&gt;&lt;ul&gt;&#10;&lt;li&gt;&lt;strong&gt;数论验证&lt;/strong&gt;：魔方常数与矩阵阶数的数学关系为代数理论提供验证案例&lt;/li&gt;&#10;&lt;li&gt;&lt;strong&gt;组合优化&lt;/strong&gt;：启发旅行商问题(TSP)、排班系统等组合优化算法设计&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h4 id="2-文化应用场景"&gt;&lt;a href="#2-%e6%96%87%e5%8c%96%e5%ba%94%e7%94%a8%e5%9c%ba%e6%99%af" class="header-anchor"&gt;&lt;/a&gt;2. 文化应用场景&#10;&lt;/h4&gt;&lt;ul&gt;&#10;&lt;li&gt;&lt;strong&gt;密码原型&lt;/strong&gt;：古代战争曾用魔方矩阵加密军事情报&lt;/li&gt;&#10;&lt;li&gt;&lt;strong&gt;艺术设计&lt;/strong&gt;：印度泰姬陵地砖、敦煌壁画均包含幻方图案&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h3 id="三r语言实现"&gt;&lt;a href="#%e4%b8%89r%e8%af%ad%e8%a8%80%e5%ae%9e%e7%8e%b0" class="header-anchor"&gt;&lt;/a&gt;三、R语言实现&#10;&lt;/h3&gt;&lt;h4 id="1-构造魔方矩阵"&gt;&lt;a href="#1-%e6%9e%84%e9%80%a0%e9%ad%94%e6%96%b9%e7%9f%a9%e9%98%b5" class="header-anchor"&gt;&lt;/a&gt;1. 构造魔方矩阵&#10;&lt;/h4&gt;&lt;pre&gt;&lt;code class="language-r"&gt;# 安装必要包&#10;if (!require(&amp;quot;magic&amp;quot;)) install.packages(&amp;quot;magic&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：magic&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：abind&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(magic)&#10;&#10;# 生成5阶魔方矩阵&#10;magic_matrix &amp;lt;- magic(5)&#10;print(magic_matrix)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4] [,5]&#10;## [1,] 9 2 25 18 11&#10;## [2,] 3 21 19 12 10&#10;## [3,] 22 20 13 6 4&#10;## [4,] 16 14 7 5 23&#10;## [5,] 15 8 1 24 17&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h4 id="2-可视化"&gt;&lt;a href="#2-%e5%8f%af%e8%a7%86%e5%8c%96" class="header-anchor"&gt;&lt;/a&gt;2. 可视化&#10;&lt;/h4&gt;&lt;pre&gt;&lt;code class="language-r"&gt;library(ggplot2)&#10;library(reshape2)&#10;&#10;# 数据重塑&#10;melted_matrix &amp;lt;- melt(magic_matrix)&#10;colnames(melted_matrix) &amp;lt;- c(&amp;quot;Row&amp;quot;, &amp;quot;Column&amp;quot;, &amp;quot;Value&amp;quot;)&#10;&#10;# 绘制热力图&#10;ggplot(melted_matrix, aes(x = Column, y = Row, fill = Value)) +&#10; geom_tile(color = &amp;quot;white&amp;quot;) +&#10; scale_fill_gradient(low = &amp;quot;#FFD700&amp;quot;, high = &amp;quot;#FF4500&amp;quot;) +&#10; geom_text(aes(label = Value), color = &amp;quot;black&amp;quot;, size = 4) +&#10; theme_minimal(base_family=&amp;quot;PingFang SC&amp;quot;) +&#10; labs(title = &amp;quot;5阶魔方矩阵可视化&amp;quot;,&#10; subtitle = &amp;quot;行、列、对角线之和均为65&amp;quot;) +&#10; coord_fixed()&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/29/magic/index_files/figure-html/unnamed-chunk-2-1.png" width="672" /&gt;&#10;&lt;p&gt;还可以写一段更简单的代码：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 安装包，如果为安装&#10;# install.packages(&amp;quot;magic&amp;quot;)&#10;library(magic)&#10;# 定义魔方矩阵函数magic.image()&#10;magic.image &amp;lt;- function(n,...){&#10; # 生成n阶魔方矩阵&#10; m&amp;lt;- magic(n)&#10; # 生成魔方矩阵热图&#10; image(m)&#10; # 添加数字标签&#10; for(j in 1:n){&#10; for(i in 1:n){&#10; text(1/(n-1)*i-1/(n-1),1+1/(n-1)-1/(n-1)*j,m[j,i])&#10; }&#10; }&#10;}&#10;# 使用函数&#10;magic.image(5)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/29/magic/index_files/figure-html/unnamed-chunk-3-1.png" width="672" /&gt;&#10;</description></item><item><title>R与矩阵运算总结</title><link>https://gewutang.cn/2011/08/27/matrix-operations/</link><pubDate>Sat, 27 Aug 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/08/27/matrix-operations/</guid><description>&lt;h1 id="1-矩阵基本操作"&gt;&lt;a href="#1-%e7%9f%a9%e9%98%b5%e5%9f%ba%e6%9c%ac%e6%93%8d%e4%bd%9c" class="header-anchor"&gt;&lt;/a&gt;1 矩阵基本操作&#10;&lt;/h1&gt;&lt;h2 id="11创建向量"&gt;&lt;a href="#11%e5%88%9b%e5%bb%ba%e5%90%91%e9%87%8f" class="header-anchor"&gt;&lt;/a&gt;1.1创建向量&#10;&lt;/h2&gt;&lt;p&gt;R里面有多种方法来创建向量（Vector），最简单的是用函数c()。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;X=c(1,2,3,4)&#10;&#10;X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;当然，还有别的方法。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;X=1:4&#10;&#10;X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;还有seq()函数。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;X=seq(1,4,length=4)&#10;&#10;X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;注意一点，R中的向量默认为列向量，如果要得到行向量需要对其进行转置。&lt;/p&gt;&#10;&lt;h2 id="12创建矩阵"&gt;&lt;a href="#12%e5%88%9b%e5%bb%ba%e7%9f%a9%e9%98%b5" class="header-anchor"&gt;&lt;/a&gt;1.2创建矩阵&#10;&lt;/h2&gt;&lt;p&gt;R中创建矩阵的方法也有很多。大致分为直接创建和由其它格式转换两种方法。&lt;/p&gt;&#10;&lt;h3 id="121直接创建矩阵"&gt;&lt;a href="#121%e7%9b%b4%e6%8e%a5%e5%88%9b%e5%bb%ba%e7%9f%a9%e9%98%b5" class="header-anchor"&gt;&lt;/a&gt;1.2.1直接创建矩阵&#10;&lt;/h3&gt;&lt;p&gt;最简单的直接创建矩阵的方法是用matrix()函数，matrix()函数的使用方法如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;args(matrix)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## function (data = NA, nrow = 1, ncol = 1, byrow = FALSE, dimnames = NULL) &#10;## NULL&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;其中，data参数输入的为矩阵的元素，不能为空；nrow参数输入的是矩阵的行数，默认为1；ncol参数输入的是矩阵的列数，默认为1；byrow参数控制矩阵元素的排列方式，TRUE表示按行排列，FALSE表示按列排列，默认为FALSE；dimnames参数输入矩阵的行名和列名，可以不输入，系统默认为NULL。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;matrix(1:6,nrow=2,ncol=3,byrow=FALSE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 3 5&#10;## [2,] 2 4 6&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;改变矩阵的行数和列数：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;matrix(1:6,nrow=3,ncol=2,byrow=FALSE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2]&#10;## [1,] 1 4&#10;## [2,] 2 5&#10;## [3,] 3 6&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;改变byrow参数：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;matrix(1:6,nrow=3,ncol=2,byrow=T)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2]&#10;## [1,] 1 2&#10;## [2,] 3 4&#10;## [3,] 5 6&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;设定矩阵的行名和列名：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;matrix(1:6,nrow=3,ncol=2,byrow=T,dimnames=list(c(&amp;quot;A&amp;quot;,&amp;quot;B&amp;quot;,&amp;quot;C&amp;quot;),c(&amp;quot;boy&amp;quot;,&amp;quot;girl&amp;quot;)))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## boy girl&#10;## A 1 2&#10;## B 3 4&#10;## C 5 6&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="122-由其它格式转换"&gt;&lt;a href="#122-%e7%94%b1%e5%85%b6%e5%ae%83%e6%a0%bc%e5%bc%8f%e8%bd%ac%e6%8d%a2" class="header-anchor"&gt;&lt;/a&gt;1.2.2 由其它格式转换&#10;&lt;/h3&gt;&lt;p&gt;也可以由其它格式的数据转换为矩阵，此时需要用到函数as.matrix()。&lt;/p&gt;&#10;&lt;h2 id="13-查看和改变矩阵的维数"&gt;&lt;a href="#13-%e6%9f%a5%e7%9c%8b%e5%92%8c%e6%94%b9%e5%8f%98%e7%9f%a9%e9%98%b5%e7%9a%84%e7%bb%b4%e6%95%b0" class="header-anchor"&gt;&lt;/a&gt;1.3 查看和改变矩阵的维数&#10;&lt;/h2&gt;&lt;p&gt;矩阵有两个维数，即行维数和列维数。在R中查看矩阵的行维数和列维数可以用函数dim()。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X=matrix(1:12,ncol=3,nrow=4)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 5 9&#10;## [2,] 2 6 10&#10;## [3,] 3 7 11&#10;## [4,] 4 8 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; dim(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 4 3&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;只返回行维数：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; dim(X)[1]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可以用函数nrow()&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;nrow(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;只返回列维数：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; dim(X)[2]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 3&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可以用函数ncol():&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; ncol(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 3&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;同时，函数dim()也可以改变矩阵的维数。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;dim(X)=c(2,6)&#10;&#10;X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4] [,5] [,6]&#10;## [1,] 1 3 5 7 9 11&#10;## [2,] 2 4 6 8 10 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="14矩阵行列的名称"&gt;&lt;a href="#14%e7%9f%a9%e9%98%b5%e8%a1%8c%e5%88%97%e7%9a%84%e5%90%8d%e7%a7%b0" class="header-anchor"&gt;&lt;/a&gt;1.4矩阵行列的名称&#10;&lt;/h2&gt;&lt;p&gt;查看矩阵的行名和列名分别用函数rownames()和函数colnames()。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;X=matrix(1:6,nrow=3,ncol=2,byrow=T,dimnames=list(c(&amp;quot;A&amp;quot;,&amp;quot;B&amp;quot;,&amp;quot;C&amp;quot;),c(&amp;quot;boy&amp;quot;,&amp;quot;girl&amp;quot;)))&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## boy girl&#10;## A 1 2&#10;## B 3 4&#10;## C 5 6&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;查看矩阵的行名：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; rownames(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;A&amp;quot; &amp;quot;B&amp;quot; &amp;quot;C&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;查看矩阵的列名：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; colnames(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;boy&amp;quot; &amp;quot;girl&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;同时也可以改变矩阵的行名和列名，比如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;rownames(X)=c(&amp;quot;E&amp;quot;,&amp;quot;F&amp;quot;,&amp;quot;G&amp;quot;)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## boy girl&#10;## E 1 2&#10;## F 3 4&#10;## G 5 6&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; colnames(X)=c(&amp;quot;man&amp;quot;,&amp;quot;woman&amp;quot;)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## man woman&#10;## E 1 2&#10;## F 3 4&#10;## G 5 6&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="15-矩阵元素的查看及其重新赋值"&gt;&lt;a href="#15-%e7%9f%a9%e9%98%b5%e5%85%83%e7%b4%a0%e7%9a%84%e6%9f%a5%e7%9c%8b%e5%8f%8a%e5%85%b6%e9%87%8d%e6%96%b0%e8%b5%8b%e5%80%bc" class="header-anchor"&gt;&lt;/a&gt;1.5 矩阵元素的查看及其重新赋值&#10;&lt;/h2&gt;&lt;p&gt;查看矩阵的某个特定元素，只需要知道该元素的行坐标和列坐标即可，例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X=matrix(1:12,nrow=4,ncol=3)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 5 9&#10;## [2,] 2 6 10&#10;## [3,] 3 7 11&#10;## [4,] 4 8 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;查看位于矩阵第二行、第三列的元素：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X[2,3]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 10&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可以重新对矩阵的元素进行赋值，将矩阵第二行、第三列的元素替换为0：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X[2,3]=0&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 5 9&#10;## [2,] 2 6 0&#10;## [3,] 3 7 11&#10;## [4,] 4 8 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;R中有一个diag()函数可以返回矩阵的全部对角元素：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X=matrix(1:9,ncol=3,nrow=3)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 4 7&#10;## [2,] 2 5 8&#10;## [3,] 3 6 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;diag(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 5 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;当然也可以对对角元素进行重新赋值：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; diag(X)=c(0,0,1)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 0 4 7&#10;## [2,] 2 0 8&#10;## [3,] 3 6 1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;当操作对象不是对称矩阵时，diag()也可以进行操作。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X=matrix(1:12,nrow=4,ncol=3)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 5 9&#10;## [2,] 2 6 10&#10;## [3,] 3 7 11&#10;## [4,] 4 8 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; diag(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 6 11&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;diag()函数还能用来生成对角矩阵：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; diag(c(1,2,3))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 0 0&#10;## [2,] 0 2 0&#10;## [3,] 0 0 3&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可以生成单位对角矩阵：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; diag(3)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 0 0&#10;## [2,] 0 1 0&#10;## [3,] 0 0 1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; diag(4)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 0 0 0&#10;## [2,] 0 1 0 0&#10;## [3,] 0 0 1 0&#10;## [4,] 0 0 0 1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;查看矩阵的上三角部分：在R中查看矩阵的上三角和下三角部分很简单。可以通过lower.tri()和upper.tir()来实现：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; args(lower.tri)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## function (x, diag = FALSE) &#10;## NULL&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; args(upper.tri)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## function (x, diag = FALSE) &#10;## NULL&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;查看上三角：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X=matrix(1:12,nrow=4,ncol=3)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 5 9&#10;## [2,] 2 6 10&#10;## [3,] 3 7 11&#10;## [4,] 4 8 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X[lower.tri(X)]&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 2 3 4 7 8 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;改变赋值：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X[lower.tri(X)]=0&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 5 9&#10;## [2,] 0 6 10&#10;## [3,] 0 0 11&#10;## [4,] 0 0 0&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h1 id="2-矩阵计算"&gt;&lt;a href="#2-%e7%9f%a9%e9%98%b5%e8%ae%a1%e7%ae%97" class="header-anchor"&gt;&lt;/a&gt;2 矩阵计算&#10;&lt;/h1&gt;&lt;h2 id="21矩阵转置"&gt;&lt;a href="#21%e7%9f%a9%e9%98%b5%e8%bd%ac%e7%bd%ae" class="header-anchor"&gt;&lt;/a&gt;2.1矩阵转置&#10;&lt;/h2&gt;&lt;p&gt;R中矩阵的转置可以用t()函数完成，例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X=matrix(1:12,nrow=4,ncol=3)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 5 9&#10;## [2,] 2 6 10&#10;## [3,] 3 7 11&#10;## [4,] 4 8 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; t(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 2 3 4&#10;## [2,] 5 6 7 8&#10;## [3,] 9 10 11 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="22矩阵的行和与列和及行平均值和列均值"&gt;&lt;a href="#22%e7%9f%a9%e9%98%b5%e7%9a%84%e8%a1%8c%e5%92%8c%e4%b8%8e%e5%88%97%e5%92%8c%e5%8f%8a%e8%a1%8c%e5%b9%b3%e5%9d%87%e5%80%bc%e5%92%8c%e5%88%97%e5%9d%87%e5%80%bc" class="header-anchor"&gt;&lt;/a&gt;2.2矩阵的行和与列和及行平均值和列均值&#10;&lt;/h2&gt;&lt;p&gt;在R中很容易计算一个矩阵的各行和和各列和以及各行的平均值和各列的平均值。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(1:12,3,4)&#10;&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 4 7 10&#10;## [2,] 2 5 8 11&#10;## [3,] 3 6 9 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; rowSums(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 22 26 30&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; rowMeans(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 5.5 6.5 7.5&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; colSums(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 6 15 24 33&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; colMeans(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 2 5 8 11&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="23行列式的值"&gt;&lt;a href="#23%e8%a1%8c%e5%88%97%e5%bc%8f%e7%9a%84%e5%80%bc" class="header-anchor"&gt;&lt;/a&gt;2.3行列式的值&#10;&lt;/h2&gt;&lt;p&gt;R中的函数det()将计算方阵A的行列式。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; X=matrix(rnorm(9),nrow=3,ncol=3)&#10;&#10; X&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] -0.6110769 -0.3434181 -1.1062389&#10;## [2,] -1.9174083 0.1106630 -0.7469723&#10;## [3,] -0.3393505 0.1931565 1.6372937&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; det(X)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] -0.9958889&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="24矩阵相加减"&gt;&lt;a href="#24%e7%9f%a9%e9%98%b5%e7%9b%b8%e5%8a%a0%e5%87%8f" class="header-anchor"&gt;&lt;/a&gt;2.4矩阵相加减&#10;&lt;/h2&gt;&lt;p&gt;矩阵元素的相加减是指维数相同的矩阵，处于同行和同列的位置的元素进行加减。实现这个功能用“＋”，“－”即可。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=B=matrix(1:12,nrow=3,ncol=4)&#10;&#10; A+B&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 2 8 14 20&#10;## [2,] 4 10 16 22&#10;## [3,] 6 12 18 24&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A-B&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 0 0 0 0&#10;## [2,] 0 0 0 0&#10;## [3,] 0 0 0 0&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="25矩阵的数乘"&gt;&lt;a href="#25%e7%9f%a9%e9%98%b5%e7%9a%84%e6%95%b0%e4%b9%98" class="header-anchor"&gt;&lt;/a&gt;2.5矩阵的数乘&#10;&lt;/h2&gt;&lt;p&gt;矩阵的数乘是指一个常数与一个矩阵相乘。设A为 &lt;code&gt;\(m\times n\)&lt;/code&gt; 矩阵，当 &lt;code&gt;\(c\ne0\)&lt;/code&gt; 时，在R中求 &lt;code&gt;\(c*A\)&lt;/code&gt; 的值，可以用符号“*”。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; c=2&#10;&#10; A=matrix(1:12,nrow=3,ncol=4)&#10;&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 4 7 10&#10;## [2,] 2 5 8 11&#10;## [3,] 3 6 9 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; c*A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 2 8 14 20&#10;## [2,] 4 10 16 22&#10;## [3,] 6 12 18 24&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;结果矩阵与原矩阵的所有相应元素都差一个常数c。&lt;/p&gt;&#10;&lt;h2 id="26矩阵相乘"&gt;&lt;a href="#26%e7%9f%a9%e9%98%b5%e7%9b%b8%e4%b9%98" class="header-anchor"&gt;&lt;/a&gt;2.6矩阵相乘&#10;&lt;/h2&gt;&lt;h3 id="261矩阵的乘法"&gt;&lt;a href="#261%e7%9f%a9%e9%98%b5%e7%9a%84%e4%b9%98%e6%b3%95" class="header-anchor"&gt;&lt;/a&gt;2.6.1矩阵的乘法&#10;&lt;/h3&gt;&lt;p&gt;A为 &lt;code&gt;\(m\times n\)&lt;/code&gt; 矩阵，B为 &lt;code&gt;\(n\times k\)&lt;/code&gt; 矩阵，在R中求 &lt;code&gt;\(A\times B\)&lt;/code&gt; ，可以符号“%*%”。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(1:12,nrow=3,ncol=4)&#10;&#10; B=matrix(1:12,nrow=4,ncol=3)&#10;&#10; A%*%B&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 70 158 246&#10;## [2,] 80 184 288&#10;## [3,] 90 210 330&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;注意: &lt;code&gt;\(B\times A\)&lt;/code&gt; 无意义，因其不符合矩阵的相乘规则。&lt;/p&gt;&#10;&lt;p&gt;若A为 &lt;code&gt;\(n\times m\)&lt;/code&gt; 矩阵，B为 &lt;code&gt;\(n\times k\)&lt;/code&gt; 矩阵，在R中求 &lt;code&gt;\(A^{'}\times B\)&lt;/code&gt; ：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(1:12,nrow=4,ncol=3)&#10;&#10; B=matrix(1:12,nrow=4,ncol=3)&#10;&#10; t(A)%*%B&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 30 70 110&#10;## [2,] 70 174 278&#10;## [3,] 110 278 446&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可以用函数crossprod()计算 &lt;code&gt;\(A^{'}\times B\)&lt;/code&gt; ：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;crossprod(A,B)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 30 70 110&#10;## [2,] 70 174 278&#10;## [3,] 110 278 446&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="262矩阵的kronecker积"&gt;&lt;a href="#262%e7%9f%a9%e9%98%b5%e7%9a%84kronecker%e7%a7%af" class="header-anchor"&gt;&lt;/a&gt;2.6.2矩阵的Kronecker积&#10;&lt;/h3&gt;&lt;p&gt;&lt;code&gt;\(n\times m\)&lt;/code&gt; 的矩阵A和 &lt;code&gt;\(h\times k\)&lt;/code&gt; 的矩阵B的Kronecker积是一个 &lt;code&gt;\(nh\times mk\)&lt;/code&gt; 维矩阵，公式为：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;A \otimes B = \begin{bmatrix}&#10;a_{11}B &amp;amp; a_{12}B &amp;amp; \cdots &amp;amp; a_{1m}B \&#10;a_{21}B &amp;amp; a_{22}B &amp;amp; \cdots &amp;amp; a_{2m}B \&#10;\vdots &amp;amp; \vdots &amp;amp; \ddots &amp;amp; \vdots \&#10;a_{n1}B &amp;amp; a_{n2}B &amp;amp; \cdots &amp;amp; a_{nm}B&#10;\end{bmatrix}&#10;$$&lt;/p&gt;&#10;&lt;p&gt;其中：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;&lt;code&gt;\(a_{ij}\)&lt;/code&gt; 表示矩阵A的第i行第j列元素&lt;/li&gt;&#10;&lt;li&gt;每个分块 &lt;code&gt;\(a_{ij}B\)&lt;/code&gt; 是原矩阵B的所有元素按 &lt;code&gt;\(a_{ij}\)&lt;/code&gt; 比例缩放后的子矩阵&lt;/li&gt;&#10;&lt;li&gt;最终结果矩阵的维度为 &lt;code&gt;\((n \cdot h) \times (m \cdot k)\)&lt;/code&gt;，即原矩阵行数乘积和新矩阵列数乘积&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;在R中Kronecker积可以用函数kronecher()来计算。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(1:4,2,2)&#10;&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2]&#10;## [1,] 1 3&#10;## [2,] 2 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; B=matrix(rep(1,4),2,2)&#10;&#10; B&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2]&#10;## [1,] 1 1&#10;## [2,] 1 1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; kronecker(A,B)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 1 3 3&#10;## [2,] 1 1 3 3&#10;## [3,] 2 2 4 4&#10;## [4,] 2 2 4 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="27矩阵的伴随矩阵"&gt;&lt;a href="#27%e7%9f%a9%e9%98%b5%e7%9a%84%e4%bc%b4%e9%9a%8f%e7%9f%a9%e9%98%b5" class="header-anchor"&gt;&lt;/a&gt;2.7矩阵的伴随矩阵&#10;&lt;/h2&gt;&lt;p&gt;求矩阵A的伴随矩阵可以用LoopAnalyst包中的函数make.adjoint()函数。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(1:12,nrow=3,ncol=4)&#10;&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 4 7 10&#10;## [2,] 2 5 8 11&#10;## [3,] 3 6 9 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; make.adjoint(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] -3 6 -3&#10;## [2,] 6 -12 6&#10;## [3,] -3 6 -3&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="28矩阵的逆和广义逆"&gt;&lt;a href="#28%e7%9f%a9%e9%98%b5%e7%9a%84%e9%80%86%e5%92%8c%e5%b9%bf%e4%b9%89%e9%80%86" class="header-anchor"&gt;&lt;/a&gt;2.8矩阵的逆和广义逆&#10;&lt;/h2&gt;&lt;h3 id="281矩阵的逆"&gt;&lt;a href="#281%e7%9f%a9%e9%98%b5%e7%9a%84%e9%80%86" class="header-anchor"&gt;&lt;/a&gt;2.8.1矩阵的逆&#10;&lt;/h3&gt;&lt;p&gt;矩阵A的逆A-1可以用函数solve()，例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(rnorm(9),nrow=3,ncol=3)&#10;&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 0.1630739 0.6387177 0.5308319&#10;## [2,] -0.8614037 0.3068824 -0.2521929&#10;## [3,] -1.4320496 0.4783913 -0.6097321&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; solve(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 0.6574602 -6.363927 3.204585&#10;## [2,] 1.6228775 -6.535581 4.116074&#10;## [3,] -0.2708487 9.818892 -5.937084&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;验证AA-1=1：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A%*%solve(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1.000000e+00 8.881784e-16 -4.440892e-16&#10;## [2,] -6.938894e-17 1.000000e+00 -2.220446e-16&#10;## [3,] -2.775558e-17 -8.881784e-16 1.000000e+00&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;用round函数可以更好的得到结果：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; round(A%*%solve(A))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 0 0&#10;## [2,] 0 1 0&#10;## [3,] 0 0 1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;solve()函数也可以用来求解方程组ax=b。&lt;/p&gt;&#10;&lt;h3 id="282矩阵的广义逆moore-penrose"&gt;&lt;a href="#282%e7%9f%a9%e9%98%b5%e7%9a%84%e5%b9%bf%e4%b9%89%e9%80%86moore-penrose" class="header-anchor"&gt;&lt;/a&gt;2.8.2矩阵的广义逆（Moore-Penrose）&#10;&lt;/h3&gt;&lt;p&gt;&lt;code&gt;\(n \times m\)&lt;/code&gt; 矩阵 &lt;code&gt;\(A^+\)&lt;/code&gt; 称为矩阵 &lt;code&gt;\(A\)&lt;/code&gt; 的 Moore-Penrose 广义逆，当且仅当它同时满足以下四个条件:&lt;/p&gt;&#10;&lt;p&gt;1.&lt;strong&gt;相容性条件&lt;/strong&gt;&#10;$$ AA^+A = A $$&lt;br&gt;&#10;该条件保证了广义逆与原矩阵相乘后能保持原矩阵的核心结构不变。&lt;/p&gt;&#10;&lt;p&gt;2.&lt;strong&gt;弱相容性条件&lt;/strong&gt;&#10;$$ A^+AA^+ = A^+ $$&lt;br&gt;&#10;表明广义逆的迭代运算具有稳定性；&lt;/p&gt;&#10;&lt;p&gt;3.&lt;strong&gt;对称性条件&lt;/strong&gt;&#10;$$ (AA^+)^T = AA^+ $$&lt;br&gt;&#10;确保乘积矩阵 &lt;code&gt;\(AA^+\)&lt;/code&gt; 是正交投影算子；&lt;/p&gt;&#10;&lt;p&gt;4.&lt;strong&gt;共轭对称性条件&lt;/strong&gt;&#10;$$ (A^+A)^T = A^+A $$&lt;br&gt;&#10;保证乘积矩阵 &lt;code&gt;\(A^+A\)&lt;/code&gt; 同样是正交投影算子。&lt;/p&gt;&#10;&lt;p&gt;其核心特性包括：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;存在唯一性：任意矩阵都存在唯一的 Moore-Penrose 逆；&lt;/li&gt;&#10;&lt;li&gt;退化特性：当 &lt;code&gt;\(A\)&lt;/code&gt; 可逆时，$A^+ = A^{-1}$；&lt;/li&gt;&#10;&lt;li&gt;计算方式：可通过奇异值分解实现 $$ A^+ = V\Sigma^+U^T $$ 其中 &lt;code&gt;\(\Sigma^+\)&lt;/code&gt; 为奇异值矩阵的伪逆。&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;R中MASS包中的ginv()函数可以计算矩阵的Moore-Penrose逆。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; library(MASS)&#10;&#10; A=matrix(1:12,nrow=3,ncol=4)&#10;&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 4 7 10&#10;## [2,] 2 5 8 11&#10;## [3,] 3 6 9 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; # solve(A) #出错&#10;&#10; ginv(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] -0.483333333 -0.03333333 0.41666667&#10;## [2,] -0.244444444 -0.01111111 0.22222222&#10;## [3,] -0.005555556 0.01111111 0.02777778&#10;## [4,] 0.233333333 0.03333333 -0.16666667&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;验证性质1：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A%*%ginv(A)%*%A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 4 7 10&#10;## [2,] 2 5 8 11&#10;## [3,] 3 6 9 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 1 4 7 10&#10;## [2,] 2 5 8 11&#10;## [3,] 3 6 9 12&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;验证性质2：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; ginv(A)%*%A%*%ginv(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] -0.483333333 -0.03333333 0.41666667&#10;## [2,] -0.244444444 -0.01111111 0.22222222&#10;## [3,] -0.005555556 0.01111111 0.02777778&#10;## [4,] 0.233333333 0.03333333 -0.16666667&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; ginv(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] -0.483333333 -0.03333333 0.41666667&#10;## [2,] -0.244444444 -0.01111111 0.22222222&#10;## [3,] -0.005555556 0.01111111 0.02777778&#10;## [4,] 0.233333333 0.03333333 -0.16666667&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;验证性质3：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A%*%ginv(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 0.8333333 0.3333333 -0.1666667&#10;## [2,] 0.3333333 0.3333333 0.3333333&#10;## [3,] -0.1666667 0.3333333 0.8333333&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; t(A%*%ginv(A))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 0.8333333 0.3333333 -0.1666667&#10;## [2,] 0.3333333 0.3333333 0.3333333&#10;## [3,] -0.1666667 0.3333333 0.8333333&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;验证性质4：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; ginv(A)%*%A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 0.7 0.4 0.1 -0.2&#10;## [2,] 0.4 0.3 0.2 0.1&#10;## [3,] 0.1 0.2 0.3 0.4&#10;## [4,] -0.2 0.1 0.4 0.7&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; t(ginv(A)%*%A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4]&#10;## [1,] 0.7 0.4 0.1 -0.2&#10;## [2,] 0.4 0.3 0.2 0.1&#10;## [3,] 0.1 0.2 0.3 0.4&#10;## [4,] -0.2 0.1 0.4 0.7&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可以不必如此麻烦来验证性质3和4，因为3和4只是表明 &lt;code&gt;\(AA^+\)&lt;/code&gt; 和 &lt;code&gt;\(A^+A\)&lt;/code&gt; 是对称矩阵。&lt;/p&gt;&#10;&lt;h3 id="283-xx-的逆"&gt;&lt;a href="#283-xx-%e7%9a%84%e9%80%86" class="header-anchor"&gt;&lt;/a&gt;2.8.3 [X^&amp;lsquo;X ]的逆&#10;&lt;/h3&gt;&lt;p&gt;很多时候，我们需要计算形如 &lt;code&gt;\(X^{'}X\)&lt;/code&gt; 的逆。这很容易实现，例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; x=matrix(rnorm(9),ncol=3,nrow=3)&#10;&#10; x&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1.8093460 1.26990532 -1.3654367&#10;## [2,] 0.4774751 0.21718498 0.2193708&#10;## [3,] -0.9058385 0.06350197 0.6108242&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; solve(crossprod(x))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 2.112090 -1.0630514 1.9311835&#10;## [2,] -1.063051 2.6346674 0.5414491&#10;## [3,] 1.931184 0.5414491 3.2942094&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;R中的strucchange包中的函数solveCrossprod()也可完成：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; library(strucchange)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：zoo&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## 载入程序包：'zoo'&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following objects are masked from 'package:base':&#10;## &#10;## as.Date, as.Date.numeric&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：sandwich&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; args(solveCrossprod)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## function (X, method = c(&amp;quot;qr&amp;quot;, &amp;quot;chol&amp;quot;, &amp;quot;solve&amp;quot;)) &#10;## NULL&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; solveCrossprod(x,method=&amp;quot;qr&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 2.112090 -1.0630514 1.9311835&#10;## [2,] -1.063051 2.6346674 0.5414491&#10;## [3,] 1.931184 0.5414491 3.2942094&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; solveCrossprod(x,method=&amp;quot;chol&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 2.112090 -1.0630514 1.9311835&#10;## [2,] -1.063051 2.6346674 0.5414491&#10;## [3,] 1.931184 0.5414491 3.2942094&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; solveCrossprod(x,method=&amp;quot;solve&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 2.112090 -1.0630514 1.9311835&#10;## [2,] -1.063051 2.6346674 0.5414491&#10;## [3,] 1.931184 0.5414491 3.2942094&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="29矩阵的特征值和特征向量"&gt;&lt;a href="#29%e7%9f%a9%e9%98%b5%e7%9a%84%e7%89%b9%e5%be%81%e5%80%bc%e5%92%8c%e7%89%b9%e5%be%81%e5%90%91%e9%87%8f" class="header-anchor"&gt;&lt;/a&gt;2.9矩阵的特征值和特征向量&#10;&lt;/h2&gt;&lt;p&gt;矩阵的谱分解（或称特征分解）是将方阵分解为特征值和特征向量构成的正交投影矩阵的线性组合。设 &lt;code&gt;\(A\)&lt;/code&gt; 是 &lt;code&gt;\(n \times n\)&lt;/code&gt; 的&lt;strong&gt;正规矩阵&lt;/strong&gt;（例如实对称矩阵、Hermitian矩阵或酉矩阵），其谱分解公式为：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;A=\sum_{i=1}^{k}\lambda_{i}E_{i}&#10;$$&lt;/p&gt;&#10;&lt;p&gt;其中：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;&lt;code&gt;\(\lambda_i\)&lt;/code&gt; 是 &lt;code&gt;\(A\)&lt;/code&gt; 的&lt;strong&gt;互异特征值&lt;/strong&gt;（共 &lt;code&gt;\(k\)&lt;/code&gt; 个不同的特征值）；&lt;/li&gt;&#10;&lt;li&gt;&lt;code&gt;\(E_i\)&lt;/code&gt; 是到 &lt;code&gt;\(\lambda_i\)&lt;/code&gt; 对应特征空间的&lt;strong&gt;正交投影矩阵&lt;/strong&gt;，满足：&#10;-&lt;strong&gt;正交性&lt;/strong&gt;：$E_i E_j = 0 \ (\forall i \neq j)$&#10;-&lt;strong&gt;幂等性&lt;/strong&gt;：$E_i^2 = E_i$&#10;-&lt;strong&gt;单位分解&lt;/strong&gt;：$\sum_{i=1}^k E_i = I_n$&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;h3 id="关键条件与性质"&gt;&lt;a href="#%e5%85%b3%e9%94%ae%e6%9d%a1%e4%bb%b6%e4%b8%8e%e6%80%a7%e8%b4%a8" class="header-anchor"&gt;&lt;/a&gt;关键条件与性质：&#10;&lt;/h3&gt;&lt;p&gt;1.&lt;strong&gt;可对角化性&lt;/strong&gt;：谱分解要求矩阵 &lt;code&gt;\(A\)&lt;/code&gt; 可对角化，正规矩阵（如对称矩阵、Hermitian矩阵）一定满足此条件；&#10;2.&lt;strong&gt;唯一性&lt;/strong&gt;：分解形式唯一，由特征值和对应的正交投影矩阵完全确定；&#10;3.&lt;strong&gt;几何意义&lt;/strong&gt;：$E_i$ 将向量投影到 &lt;code&gt;\(\lambda_i\)&lt;/code&gt; 的特征空间，$A$ 的作用相当于在不同特征方向上按 &lt;code&gt;\(\lambda_i\)&lt;/code&gt; 缩放；&#10;4.&lt;strong&gt;特殊情形&lt;/strong&gt;：若 &lt;code&gt;\(A\)&lt;/code&gt; 的特征值互异（无重复），则 &lt;code&gt;\(E_i = v_i v_i^T / \|v_i\|^2\)&lt;/code&gt;（$v_i$ 为标准正交特征向量）。&lt;/p&gt;&#10;&lt;p&gt;比如：&lt;/p&gt;&#10;&lt;p&gt;若 &lt;code&gt;\(A = \begin{bmatrix} 2 &amp;amp; 1 \\ 1 &amp;amp; 2 \end{bmatrix}\)&lt;/code&gt;，其特征值 &lt;code&gt;\(\lambda_1=3\)&lt;/code&gt;, &lt;code&gt;\(\lambda_2=1\)&lt;/code&gt;，对应投影矩阵：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;E_1 = \frac{1}{2}\begin{bmatrix} 1 &amp;amp; 1 \ 1 &amp;amp; 1 \end{bmatrix}, \quad E_2 = \frac{1}{2}\begin{bmatrix} 1 &amp;amp; -1 \ -1 &amp;amp; 1 \end{bmatrix}&#10;$$&lt;/p&gt;&#10;&lt;p&gt;则谱分解为：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;A = 3E_1 + 1E_2&#10;$$&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; args(eigen)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## function (x, symmetric, only.values = FALSE, EISPACK = FALSE) &#10;## NULL&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;其中，x参数输入矩阵；symmetric参数判断矩阵是否为对称矩阵，如果参数为空，系统将自动检测矩阵的对称性。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(1:9,nrow=3,ncol=3)&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 4 7&#10;## [2,] 2 5 8&#10;## [3,] 3 6 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; Aeigen=eigen(A)&#10;&#10; Aeigen&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## eigen() decomposition&#10;## $values&#10;## [1] 1.611684e+01 -1.116844e+00 -5.700691e-16&#10;## &#10;## $vectors&#10;## [,1] [,2] [,3]&#10;## [1,] -0.4645473 -0.8829060 0.4082483&#10;## [2,] -0.5707955 -0.2395204 -0.8164966&#10;## [3,] -0.6770438 0.4038651 0.4082483&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;得到矩阵A的特征值：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; Aeigen$values&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1.611684e+01 -1.116844e+00 -5.700691e-16&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;得到矩阵A的特征向量：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; Aeigen$vectors&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] -0.4645473 -0.8829060 0.4082483&#10;## [2,] -0.5707955 -0.2395204 -0.8164966&#10;## [3,] -0.6770438 0.4038651 0.4082483&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h1 id="3-矩阵高级操作"&gt;&lt;a href="#3-%e7%9f%a9%e9%98%b5%e9%ab%98%e7%ba%a7%e6%93%8d%e4%bd%9c" class="header-anchor"&gt;&lt;/a&gt;3 矩阵高级操作&#10;&lt;/h1&gt;&lt;h2 id="31-choleskey分解"&gt;&lt;a href="#31-choleskey%e5%88%86%e8%a7%a3" class="header-anchor"&gt;&lt;/a&gt;3.1 Choleskey分解&#10;&lt;/h2&gt;&lt;p&gt;对于正定矩阵A，可以对其进行Choleskey分解，$A=P^{&amp;rsquo;}P$ ，其中P为上三角矩阵，在R中可以用函数chol()。例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=diag(3)+1&#10;&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 2 1 1&#10;## [2,] 1 2 1&#10;## [3,] 1 1 2&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; chol(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1.414214 0.7071068 0.7071068&#10;## [2,] 0.000000 1.2247449 0.4082483&#10;## [3,] 0.000000 0.0000000 1.1547005&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;验证$A=P^{&amp;rsquo;}P$ ：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; t(chol(A))%*%chol(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 2 1 1&#10;## [2,] 1 2 1&#10;## [3,] 1 1 2&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可以用crossprod()函数：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; crossprod(chol(A),chol(A))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 2 1 1&#10;## [2,] 1 2 1&#10;## [3,] 1 1 2&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;可以用Choleskey分解来计算矩阵的行列式：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; prod(diag(chol(A))^2)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; det(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 4&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;也可以用Choleskey分解来计算矩阵的逆，这时候可以用到函数chol2inv():&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; chol2inv(chol(A))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 0.75 -0.25 -0.25&#10;## [2,] -0.25 0.75 -0.25&#10;## [3,] -0.25 -0.25 0.75&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; solve(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 0.75 -0.25 -0.25&#10;## [2,] -0.25 0.75 -0.25&#10;## [3,] -0.25 -0.25 0.75&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="32-奇异值分解"&gt;&lt;a href="#32-%e5%a5%87%e5%bc%82%e5%80%bc%e5%88%86%e8%a7%a3" class="header-anchor"&gt;&lt;/a&gt;3.2 奇异值分解&#10;&lt;/h2&gt;&lt;p&gt;A为$m\times n$ 矩阵，矩阵的秩为r。A可以分解为$A=UDV^{&amp;rsquo;}$ ，其中:$U^{&amp;rsquo;}U=V^{&amp;rsquo;}V=I$ 。在R中可以用函数svd()来完成奇异值分解。&lt;/p&gt;&#10;&lt;p&gt;例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(1:18,3,6)&#10;&#10; A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4] [,5] [,6]&#10;## [1,] 1 4 7 10 13 16&#10;## [2,] 2 5 8 11 14 17&#10;## [3,] 3 6 9 12 15 18&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; svd(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $d&#10;## [1] 4.589453e+01 1.640705e+00 1.366522e-15&#10;## &#10;## $u&#10;## [,1] [,2] [,3]&#10;## [1,] -0.5290354 0.74394551 0.4082483&#10;## [2,] -0.5760715 0.03840487 -0.8164966&#10;## [3,] -0.6231077 -0.66713577 0.4082483&#10;## &#10;## $v&#10;## [,1] [,2] [,3]&#10;## [1,] -0.07736219 -0.71960032 -0.4076688&#10;## [2,] -0.19033085 -0.50893247 0.5745647&#10;## [3,] -0.30329950 -0.29826463 -0.0280114&#10;## [4,] -0.41626816 -0.08759679 0.2226621&#10;## [5,] -0.52923682 0.12307105 -0.6212052&#10;## [6,] -0.64220548 0.33373889 0.2596585&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; svd(A)$u%*%diag(svd(A)$d)%*%t(svd(A)$v)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3] [,4] [,5] [,6]&#10;## [1,] 1 4 7 10 13 16&#10;## [2,] 2 5 8 11 14 17&#10;## [3,] 3 6 9 12 15 18&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="33-qr分解"&gt;&lt;a href="#33-qr%e5%88%86%e8%a7%a3" class="header-anchor"&gt;&lt;/a&gt;3.3 QR分解&#10;&lt;/h2&gt;&lt;p&gt;A为$m\times n$ 矩阵可以进行QR分解:$A=QR$ ，其中$Q^{&amp;rsquo;}Q=I$ ，在R中可以用函数qr()来完成这个过程，例如：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; A=matrix(1:12,4,3)&#10;&#10; qr(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## $qr&#10;## [,1] [,2] [,3]&#10;## [1,] -5.4772256 -12.7801930 -2.008316e+01&#10;## [2,] 0.3651484 -3.2659863 -6.531973e+00&#10;## [3,] 0.5477226 -0.3781696 1.601186e-15&#10;## [4,] 0.7302967 -0.9124744 -5.547002e-01&#10;## &#10;## $rank&#10;## [1] 2&#10;## &#10;## $qraux&#10;## [1] 1.182574 1.156135 1.832050&#10;## &#10;## $pivot&#10;## [1] 1 2 3&#10;## &#10;## attr(,&amp;quot;class&amp;quot;)&#10;## [1] &amp;quot;qr&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;Rank返回的是矩阵的秩。Qr项包含了Q矩阵和R矩阵的信息。要想得到Q矩阵和R矩阵，可以用qr.Q()函数和qr.R()函数：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;qr.Q(qr(A))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] -0.1825742 -8.164966e-01 -0.4000874&#10;## [2,] -0.3651484 -4.082483e-01 0.2546329&#10;## [3,] -0.5477226 -1.665335e-16 0.6909965&#10;## [4,] -0.7302967 4.082483e-01 -0.5455419&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;qr.R(qr(A))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] -5.477226 -12.780193 -2.008316e+01&#10;## [2,] 0.000000 -3.265986 -6.531973e+00&#10;## [3,] 0.000000 0.000000 1.601186e-15&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h1 id="4-解方程组"&gt;&lt;a href="#4-%e8%a7%a3%e6%96%b9%e7%a8%8b%e7%bb%84" class="header-anchor"&gt;&lt;/a&gt;4 解方程组&#10;&lt;/h1&gt;&lt;h2 id="41普通方程组"&gt;&lt;a href="#41%e6%99%ae%e9%80%9a%e6%96%b9%e7%a8%8b%e7%bb%84" class="header-anchor"&gt;&lt;/a&gt;4.1普通方程组&#10;&lt;/h2&gt;&lt;p&gt;解普通方程组可以用函数solve()，solve()的基本用法是solve(A,b)，其中，A为方程组的系数矩阵，b为方程组的右端。例如：&lt;/p&gt;&#10;&lt;p&gt;已知方程组：&lt;/p&gt;&#10;&lt;p&gt;$$&#10;\begin{cases}&#10;2x_1+2x_3=1\&#10;2x_1+x_2+2x_3=2\&#10;2x_1+x_2=3&#10;\end{cases}&#10;$$&lt;/p&gt;&#10;&lt;p&gt;解法如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;A=matrix(&#10;c(2,0,2,&#10; 2,1,2,&#10; 2,1,0),&#10; byrow=TRUE,nrow=3&#10;)&#10;&#10;b=1:3&#10;&#10;b&#10;&#10;solve(A,b)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;即$x_1=1$ ，$x_2=1$ ，$x_3=-0.5$ 。&lt;/p&gt;&#10;&lt;h2 id="42-特殊方程组"&gt;&lt;a href="#42-%e7%89%b9%e6%ae%8a%e6%96%b9%e7%a8%8b%e7%bb%84" class="header-anchor"&gt;&lt;/a&gt;4.2 特殊方程组&#10;&lt;/h2&gt;&lt;p&gt;对于系数矩阵是上三角矩阵和下三角矩阵的方程组。R中提供了backsolve()和fowardsolve()来解决这个问题。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;backsolve(r, x, k=ncol(r), upper.tri=TRUE, transpose=FALSE)&#10;&#10;forwardsolve(l, x, k=ncol(l), upper.tri=FALSE, transpose=FALSE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;这两个函数都是符合操作的函数，大致可以分为三个步骤：&lt;/p&gt;&#10;&lt;ol&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;通过将系数矩阵的上三角或者下三角变为0的到新的系数矩阵,这通过upper.tri参数来实现，若upper.tri=TRUR，上三角不为0。&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;通过将对步骤1中得到的新系数矩阵进行转置得到新的系数矩阵，这通过transpose参数实现，若transpose=FALSE，则步骤1中得到的系数矩阵将被转置。&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;根据步骤2得到的系数矩阵来解方程组。&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ol&gt;&#10;&lt;p&gt;$$&#10;\begin{cases}&#10;X_1+4X_2+7X_3=1\&#10;2X_1+5X_2+8X_3=2\&#10;3X_1+6X_2+9X_3=3&#10;\end{cases}&#10;$$&lt;/p&gt;&#10;&lt;p&gt;方程组的系数矩阵为：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;A &amp;lt;- matrix(&#10; c(1,4,7,&#10; 2,5,8,&#10; 3,6,9),&#10; byrow=TRUE,&#10; nrow = 3&#10;)&#10;&#10;b=1:3&#10;&#10;backsolve(A,b,upper.tri=T,transpose=F)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] -0.8000000 -0.1333333 0.3333333&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;过程分解：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;upper.tri=T，说明系数矩阵的上三角不为0。&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;B=A&#10;&#10;B[lower.tri(B)]=0&#10;&#10;B&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 4 7&#10;## [2,] 0 5 8&#10;## [3,] 0 0 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;transpose=F说明系数矩阵未被转置。&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;li&gt;&#10;&lt;p&gt;解方程：&lt;/p&gt;&#10;&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;solve(B,b)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] -0.8000000 -0.1333333 0.3333333&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h1 id="5-其它"&gt;&lt;a href="#5-%e5%85%b6%e5%ae%83" class="header-anchor"&gt;&lt;/a&gt;5 其它&#10;&lt;/h1&gt;&lt;h2 id="51矩阵的向量化"&gt;&lt;a href="#51%e7%9f%a9%e9%98%b5%e7%9a%84%e5%90%91%e9%87%8f%e5%8c%96" class="header-anchor"&gt;&lt;/a&gt;5.1矩阵的向量化&#10;&lt;/h2&gt;&lt;p&gt;将矩阵向量化有时候是必要的。矩阵的向量化可以通过as.vector()来实现：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;A &amp;lt;- matrix(1:9,nrow=3)&#10;&#10;A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 4 7&#10;## [2,] 2 5 8&#10;## [3,] 3 6 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;将矩阵元素向量化：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;as.vector(A)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4 5 6 7 8 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 4 7&#10;## [2,] 2 5 8&#10;## [3,] 3 6 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;将矩阵的方阵部分元素向量化：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;as.vector(A[1:min(dim(A)),1:min(dim(A))])&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] 1 2 3 4 5 6 7 8 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="52矩阵的合并"&gt;&lt;a href="#52%e7%9f%a9%e9%98%b5%e7%9a%84%e5%90%88%e5%b9%b6" class="header-anchor"&gt;&lt;/a&gt;5.2矩阵的合并&#10;&lt;/h2&gt;&lt;h3 id="521矩阵的列合并"&gt;&lt;a href="#521%e7%9f%a9%e9%98%b5%e7%9a%84%e5%88%97%e5%90%88%e5%b9%b6" class="header-anchor"&gt;&lt;/a&gt;5.2.1矩阵的列合并&#10;&lt;/h3&gt;&lt;p&gt;矩阵的列合并可以通过cbind()来实现。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 4 7&#10;## [2,] 2 5 8&#10;## [3,] 3 6 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;B=1:3&#10;&#10;cbind(A,B)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## B&#10;## [1,] 1 4 7 1&#10;## [2,] 2 5 8 2&#10;## [3,] 3 6 9 3&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h3 id="522矩阵的行合并"&gt;&lt;a href="#522%e7%9f%a9%e9%98%b5%e7%9a%84%e8%a1%8c%e5%90%88%e5%b9%b6" class="header-anchor"&gt;&lt;/a&gt;5.2.2矩阵的行合并&#10;&lt;/h3&gt;&lt;p&gt;矩阵的行合并可以通过rbind()来实现。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;A&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## [1,] 1 4 7&#10;## [2,] 2 5 8&#10;## [3,] 3 6 9&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;B=1:3&#10;&#10;rbind(A,B)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [,1] [,2] [,3]&#10;## 1 4 7&#10;## 2 5 8&#10;## 3 6 9&#10;## B 1 2 3&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>R语言绘制维恩图</title><link>https://gewutang.cn/2011/08/27/venn/</link><pubDate>Sat, 27 Aug 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/08/27/venn/</guid><description>&lt;p&gt;很久之前整理的关于R绘制维恩图的资料，虽然，用R绘制维恩图并不是很常见，还是记下一笔，以备需要者参考。&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# Gplots包&#10;library(gplots)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## 载入程序包：'gplots'&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following object is masked from 'package:stats':&#10;## &#10;## lowess&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;A&amp;lt;- 1:20&#10;B&amp;lt;- 1:20&#10;C&amp;lt;- 2:20&#10;D&amp;lt;- 3:21&#10;&#10;input&amp;lt;-list(A,B,C,D)&#10;input&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [[1]]&#10;## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20&#10;## &#10;## [[2]]&#10;## [1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20&#10;## &#10;## [[3]]&#10;## [1] 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20&#10;## &#10;## [[4]]&#10;## [1] 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;venn(input)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-1.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;A&amp;lt;- as.logical(rbinom(100, 1, 0.2))&#10;B&amp;lt;- as.logical(rbinom(100, 1, 0.7))&#10;C&amp;lt;- as.logical(rbinom(100, 1, 0.2))&#10;D&amp;lt;- as.logical(rbinom(100, 1, 0.1))&#10;&#10;input&amp;lt;-data.frame(A,B,C,D)&#10;venn(input)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-2.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;tmp &amp;lt;- venn(input, simplify=TRUE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Warning in drawVennDiagram(data = counts, small = small, showSetLogicLabel = showSetLogicLabel, : Not shown: 0101 contains 2&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-3.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;tmp&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## num A B C D&#10;## 0000 0 0 0 0 0&#10;## 0001 1 0 0 0 1&#10;## 0010 4 0 0 1 0&#10;## 0011 0 0 0 1 1&#10;## 0100 36 0 1 0 0&#10;## 0101 2 0 1 0 1&#10;## 0110 6 0 1 1 0&#10;## 0111 1 0 1 1 1&#10;## 1000 5 1 0 0 0&#10;## 1001 0 1 0 0 1&#10;## 1010 0 1 0 1 0&#10;## 1011 1 1 0 1 1&#10;## 1100 15 1 1 0 0&#10;## 1101 1 1 1 0 1&#10;## 1110 6 1 1 1 0&#10;## 1111 1 1 1 1 1&#10;## attr(,&amp;quot;intersections&amp;quot;)&#10;## attr(,&amp;quot;intersections&amp;quot;)$A&#10;## [1] &amp;quot;18&amp;quot; &amp;quot;29&amp;quot; &amp;quot;32&amp;quot; &amp;quot;54&amp;quot; &amp;quot;58&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$B&#10;## [1] &amp;quot;12&amp;quot; &amp;quot;14&amp;quot; &amp;quot;19&amp;quot; &amp;quot;22&amp;quot; &amp;quot;28&amp;quot; &amp;quot;30&amp;quot; &amp;quot;34&amp;quot; &amp;quot;36&amp;quot; &amp;quot;40&amp;quot; &amp;quot;43&amp;quot; &amp;quot;45&amp;quot; &amp;quot;46&amp;quot; &#10;## [13] &amp;quot;51&amp;quot; &amp;quot;52&amp;quot; &amp;quot;53&amp;quot; &amp;quot;57&amp;quot; &amp;quot;60&amp;quot; &amp;quot;66&amp;quot; &amp;quot;67&amp;quot; &amp;quot;68&amp;quot; &amp;quot;69&amp;quot; &amp;quot;70&amp;quot; &amp;quot;73&amp;quot; &amp;quot;75&amp;quot; &#10;## [25] &amp;quot;76&amp;quot; &amp;quot;77&amp;quot; &amp;quot;78&amp;quot; &amp;quot;80&amp;quot; &amp;quot;81&amp;quot; &amp;quot;87&amp;quot; &amp;quot;88&amp;quot; &amp;quot;89&amp;quot; &amp;quot;92&amp;quot; &amp;quot;94&amp;quot; &amp;quot;98&amp;quot; &amp;quot;100&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$C&#10;## [1] &amp;quot;6&amp;quot; &amp;quot;10&amp;quot; &amp;quot;33&amp;quot; &amp;quot;84&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$D&#10;## [1] &amp;quot;79&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$`A:B`&#10;## [1] &amp;quot;2&amp;quot; &amp;quot;5&amp;quot; &amp;quot;9&amp;quot; &amp;quot;13&amp;quot; &amp;quot;17&amp;quot; &amp;quot;21&amp;quot; &amp;quot;25&amp;quot; &amp;quot;26&amp;quot; &amp;quot;27&amp;quot; &amp;quot;38&amp;quot; &amp;quot;39&amp;quot; &amp;quot;44&amp;quot; &amp;quot;49&amp;quot; &amp;quot;50&amp;quot; &amp;quot;56&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$`B:C`&#10;## [1] &amp;quot;20&amp;quot; &amp;quot;71&amp;quot; &amp;quot;72&amp;quot; &amp;quot;82&amp;quot; &amp;quot;83&amp;quot; &amp;quot;97&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$`B:D`&#10;## [1] &amp;quot;62&amp;quot; &amp;quot;63&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$`A:B:C`&#10;## [1] &amp;quot;3&amp;quot; &amp;quot;11&amp;quot; &amp;quot;47&amp;quot; &amp;quot;74&amp;quot; &amp;quot;85&amp;quot; &amp;quot;95&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$`A:B:D`&#10;## [1] &amp;quot;96&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$`A:C:D`&#10;## [1] &amp;quot;7&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$`B:C:D`&#10;## [1] &amp;quot;23&amp;quot;&#10;## &#10;## attr(,&amp;quot;intersections&amp;quot;)$`A:B:C:D`&#10;## [1] &amp;quot;37&amp;quot;&#10;## &#10;## attr(,&amp;quot;class&amp;quot;)&#10;## [1] &amp;quot;venn&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;venn(input, showSetLogicLabel=TRUE)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-4.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# asbio包&#10;library(asbio)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：tcltk&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;Venn(A=.3,B=.2,AandB=.06)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-5.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# limma包&#10;# install.packages(&amp;quot;BiocManager&amp;quot;)&#10;# BiocManager::install(&amp;quot;limma&amp;quot;)&#10;library(limma)&#10;Y &amp;lt;- matrix(rnorm(100*6),100,6)&#10;Y[1:10,3:4] &amp;lt;- Y[1:10,3:4]+3&#10;Y[1:20,5:6] &amp;lt;- Y[1:20,5:6]+3&#10;design &amp;lt;- cbind(1,c(0,0,1,1,0,0),c(0,0,0,0,1,1))&#10;fit &amp;lt;- eBayes(lmFit(Y,design))&#10;results &amp;lt;- decideTests(fit)&#10;a &amp;lt;- vennCounts(results)&#10;print(a)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## x1 x2 x3 Counts&#10;## 1 0 0 0 88&#10;## 2 0 0 1 8&#10;## 3 0 1 0 0&#10;## 4 0 1 1 4&#10;## 5 1 0 0 0&#10;## 6 1 0 1 0&#10;## 7 1 1 0 0&#10;## 8 1 1 1 0&#10;## attr(,&amp;quot;class&amp;quot;)&#10;## [1] &amp;quot;VennCounts&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;vennDiagram(a)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-6.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;vennDiagram(results,include=c(&amp;quot;up&amp;quot;,&amp;quot;down&amp;quot;),counts.col=c(&amp;quot;red&amp;quot;,&amp;quot;green&amp;quot;))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-7.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# venneuler包&#10;&#10;library(venneuler)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：rJava&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;vd &amp;lt;- venneuler(c(A=0.3, B=0.3, C=1.1, &amp;quot;A&amp;amp;B&amp;quot;=0.1, &amp;quot;A&amp;amp;C&amp;quot;=0.2, &amp;quot;B&amp;amp;C&amp;quot;=0.1 ,&amp;quot;A&amp;amp;B&amp;amp;C&amp;quot;=0.1))&#10;&#10;plot(vd)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-8.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;m &amp;lt;- data.frame(elements=c(&amp;quot;1&amp;quot;,&amp;quot;2&amp;quot;,&amp;quot;2&amp;quot;,&amp;quot;2&amp;quot;,&amp;quot;3&amp;quot;),sets=c(&amp;quot;A&amp;quot;,&amp;quot;A&amp;quot;,&amp;quot;B&amp;quot;,&amp;quot;C&amp;quot;,&amp;quot;C&amp;quot;))&#10; &#10;v &amp;lt;- venneuler(m)&#10;&#10;plot(v)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-9.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;m &amp;lt;- as.matrix(data.frame(A=c(1.5, 0.2, 0.4, 0, 0),B=c(0, 0.2, 0, 1, 0), C=c(0, 0, 0.3, 0, 1)))&#10;&#10;v &amp;lt;- venneuler(m &amp;gt; 0)&#10;&#10;plot(v)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-10.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;v &amp;lt;- venneuler(m)&#10;&#10;plot(v)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-11.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# Vennerable包&#10;&#10;# BiocManager::install(&amp;quot;graph&amp;quot;)&#10;# BiocManager::install(&amp;quot;RBGL&amp;quot;)&#10;# BiocManager::install(&amp;quot;reshape&amp;quot;)&#10;# install.packages(&amp;quot;Vennerable&amp;quot;, repos=&amp;quot;http://R-Forge.R-project.org&amp;quot;)&#10;&#10;library(Vennerable)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：graph&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：BiocGenerics&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：generics&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## 载入程序包：'generics'&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following objects are masked from 'package:base':&#10;## &#10;## as.difftime, as.factor, as.ordered, intersect, is.element, setdiff,&#10;## setequal, union&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## 载入程序包：'BiocGenerics'&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following objects are masked from 'package:rJava':&#10;## &#10;## anyDuplicated, duplicated, unique&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following object is masked from 'package:limma':&#10;## &#10;## plotMA&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following objects are masked from 'package:stats':&#10;## &#10;## IQR, mad, sd, var, xtabs&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following objects are masked from 'package:base':&#10;## &#10;## anyDuplicated, aperm, append, as.data.frame, basename, cbind,&#10;## colnames, dirname, do.call, duplicated, eval, evalq, Filter, Find,&#10;## get, grep, grepl, is.unsorted, lapply, Map, mapply, match, mget,&#10;## order, paste, pmax, pmax.int, pmin, pmin.int, Position, rank,&#10;## rbind, Reduce, rownames, sapply, saveRDS, table, tapply, unique,&#10;## unsplit, which.max, which.min&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：RBGL&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：grid&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：lattice&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：RColorBrewer&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：reshape&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：gtools&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：xtable&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#10;## 载入程序包：'Vennerable'&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## The following object is masked from 'package:asbio':&#10;## &#10;## Venn&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;Venn(n=3)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## A Venn object on 3 sets named&#10;## 1,2,3 &#10;## 000 100 010 110 001 101 011 111 &#10;## 1 1 1 1 1 1 1 1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;plot(Venn(n=3))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-12.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;data(StemCell)&#10;w &amp;lt;- Venn(Sets=StemCell[1:2])&#10;Weights(w)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 00 10 01 11 &#10;## 0 219 875 404&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;plot(w)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-13.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;Weights(w) &amp;lt;- 1:4&#10;plot(w)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/27/venn/index_files/figure-html/unnamed-chunk-1-14.png" width="672" /&gt;&#10;</description></item><item><title>draw.circle:R中的绘圆利器</title><link>https://gewutang.cn/2011/08/03/a-powerful-tool-to-draw-circle-with-r/</link><pubDate>Wed, 03 Aug 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/08/03/a-powerful-tool-to-draw-circle-with-r/</guid><description>&lt;p&gt;R用户经常要在图形中绘圆，如果你是其中的一员的话，你就不得不了解一下plotrix包中的draw.circle()函数。draw.circle()函数的优点有：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;任意指定位置&lt;/li&gt;&#10;&lt;li&gt;随意设定圆内的颜色&lt;/li&gt;&#10;&lt;li&gt;随意设定圆的线型&lt;/li&gt;&#10;&lt;li&gt;随意设定圆线的颜色&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(plotrix)&#10;plot(1:5,seq(1,10,length=5),type=&amp;quot;n&amp;quot;,xlab=&amp;quot;&amp;quot;,ylab=&amp;quot;&amp;quot;,main=&amp;quot;Test draw.circle()&amp;quot;)&#10;draw.circle(2,4,c(1,0.66,0.33),border=&amp;quot;purple&amp;quot;,&#10;col=c(&amp;quot;#ff00ff&amp;quot;,&amp;quot;#ff77ff&amp;quot;,&amp;quot;#ffccff&amp;quot;),lty=1,lwd=1)&#10;draw.circle(2.5,8,0.6,border=&amp;quot;red&amp;quot;,lty=3,lwd=3)&#10;draw.circle(4,3,0.7,border=&amp;quot;green&amp;quot;,lty=1,lwd=1)&#10;draw.circle(3.5,7,0.8,border=&amp;quot;blue&amp;quot;,lty=2,lwd=2)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/08/03/a-powerful-tool-to-draw-circle-with-r/index_files/figure-html/unnamed-chunk-1-1.png" width="672" /&gt;&#10;</description></item><item><title>用四个参数拟合大象</title><link>https://gewutang.cn/2011/06/23/use-four-parameters-to-fit-an-elephant/</link><pubDate>Thu, 23 Jun 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/06/23/use-four-parameters-to-fit-an-elephant/</guid><description>&lt;p&gt;冯·诺依曼说过一句话，&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;With four parameters I can fit an elephant, and with five I can make him wiggle his trunk.&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;冯·诺依曼说这句话的时候，当然是一种隐喻。他的大致意思是说，当一个模型能够完美拟合一个数据集的时候，不要沾沾自喜或者得意到脱掉下巴。因为之所以出现这种情况很可能是因为模型的参数太多，而不是模型的形式很好。如果给模型足够多的参数，我们实际上可以完美的拟合任何数据集。&lt;/p&gt;&#10;&lt;p&gt;虽然用四个参数来拟合大象并非是冯·诺依曼的本意，可是打他说出来这句话起，就有很多人前赴后继地研究如何用四个参数来真的拟合出来一头大象。后来，Jurgen Mayer, Khaled Khairy, and Jonathon Howard在论文“Drawing an elephant with four complex parameters”当真实现了这句话。&lt;/p&gt;&#10;&lt;p&gt;绘制大象的R代码如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;p1=50-30i&#10;p2=18+8i&#10;p3=12-10i&#10;p4=-14-60i&#10;p5=40+20i&#10;&#10;fourier=function(tt,CC){&#10;f=numeric(length(tt));&#10;A=Re(CC);&#10;B=Im(CC);&#10;k=1:length(CC);&#10;for(i in 1:length(tt)){&#10;co=cos(tt[i]*k)&#10;si=sin(tt[i]*k)&#10;f[i]=sum(A*co+B*si)&#10;f&#10;}&#10;f&#10;}&#10;&#10;elephant=function(tt,p1,p2,p3,p4,p5){&#10;n=6&#10;Cx=complex(n);&#10;Cy=complex(n);&#10;Cx[1]=Re(p1)*1i&#10;Cx[2]=Re(p2)*1i&#10;Cx[3]=Re(p3)&#10;Cx[5]=Re(p4)&#10;Cy[1]=Im(p4)+Im(p1)*1i&#10;Cy[2]=Im(p2)*1i&#10;Cy[3]=Im(p3)*1i&#10;&#10;x=fourier(tt,Cx)&#10;y=fourier(tt,Cy)&#10;res=cbind(y,-x)&#10;res&#10;}&#10;&#10;tt=seq(from=0,to=2*pi,length=100)&#10;el=elephant(tt,p1,p2,p3,p4,p5)&#10;&#10;plot(el,type=&amp;quot;l&amp;quot;,col=&amp;quot;red&amp;quot;,ylab=&amp;quot;&amp;quot;,xlab=&amp;quot;&amp;quot;,lwd=2)&#10;points(Im(p5),Im(p5),pch=20,col=&amp;quot;red&amp;quot;) &#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2011/06/23/use-four-parameters-to-fit-an-elephant/index_files/figure-html/unnamed-chunk-1-1.png" width="672" /&gt;&#10;</description></item><item><title>获取交易明细数据</title><link>https://gewutang.cn/2011/05/16/use-r-to-get-trade-details/</link><pubDate>Mon, 16 May 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/05/16/use-r-to-get-trade-details/</guid><description>&lt;p&gt;或许是因为大学期间经常不吃早饭的原因，最终我的侥幸心理被无情的现实打破，不幸于上周罹患反流性食道炎。因为身体十分不适，所以也懒得写东西。&lt;/p&gt;&#10;&lt;p&gt;数天前，我在COS上发布了一个获取股市交易明细的R代码。几经修缮，臻于完整。将来我会将它们放入iquant包中。&lt;/p&gt;&#10;&lt;p&gt;两个示例如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;source(&amp;quot;get.nowdata.r&amp;quot;); #载入代码&#10;nowdata=get.nowdata(&amp;quot;000061&amp;quot;); #获取000061的交易明细数据&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;返回结果如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;$symbol&#10;[1] &amp;quot;000061&amp;quot;&#10;&#10;$Company&#10;[1] &amp;quot;农产品&amp;quot;&#10;&#10;$Date&#10;[1] &amp;quot;2011年05月16日 15:00&amp;quot;&#10;&#10;$Details&#10;Time Volum Price Turnover Orders NIO&#10;1    09:25:02   133 17.57    23.44   平盘   0&#10;2    09:30:02   251 17.60    44.21   流入   2&#10;3    09:30:32    68 17.60    11.97   平盘   0&#10;4    09:30:52     2 17.65     0.35   流入   2&#10;5    09:31:02     8 17.78     1.42   流入   2&#10;6    09:31:12     4 17.65     0.71   流出   1&#10;7    09:31:22    11 17.80     1.96   流入   2&#10;8    09:31:32     6 17.78     1.07   流入   2&#10;9    09:31:42    10 17.66     1.91   平盘   0&#10;10   09:31:47     6 17.73     1.06   流入   2&#10;11   09:32:22    10 17.73     1.77   流入   2&#10;12   09:32:37     3 17.73     0.53   流出   1&#10;13   09:32:47     8 17.73     1.42   流出   1&#10;14   09:32:52     4 17.73     0.71   流出   1&#10;15   09:32:57    74 17.67    13.10   流出   1&#10;16   09:33:12    10 17.73     1.77   流入   2&#10;17   09:33:32     4 17.73     0.71   流入   2&#10;18   09:33:37     6 17.73     1.06   流出   1&#10;19   09:33:52    14 17.75     2.48   流入   2&#10;20   09:34:02    12 17.73     2.12   流入   2&#10;21   09:34:22     2 17.69     0.35   流出   1&#10;22   09:34:27     3 17.69     0.53   流出   1&#10;23   09:34:42     2 17.69     0.35   流出   1&#10;24   09:34:47     1 17.73     0.18   流入   2&#10;25   09:34:57     9 17.69     1.59   流出   1&#10;26   09:35:07     1 17.69     0.18   流出   1&#10;27   09:35:17    82 17.75    14.55   流入   2&#10;28   09:35:22    13 17.75     2.31   流出   1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;获得历史数据：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;source(&amp;quot;get.historydata.r&amp;quot;); #载入get.historydata.r&#10;historydata=get.historydata(&amp;quot;000061&amp;quot;,&amp;quot;20110401&amp;quot;); #获取000061在2011年4月1日的交易明细数据&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;结果如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code&gt;$symbol&#10;[1] &amp;quot;000061&amp;quot;&#10;&#10;$Company&#10;[1] &amp;quot;农产品&amp;quot;&#10;&#10;$Date&#10;[1] &amp;quot;2011年4月01日&amp;quot;&#10;&#10;$Details&#10;Time Volum Price Turnover Orders NIO&#10;1    09:25:06    84 16.70    14.03   平盘   0&#10;2    09:30:06    72 16.72    12.03   流入   2&#10;3    09:30:11     5 16.74     0.84   流入   2&#10;4    09:30:16    18 16.74     3.01   流入   2&#10;5    09:30:21    18 16.74     3.01   流入   2&#10;6    09:30:31    11 16.72     1.84   流出   1&#10;7    09:30:36    50 16.75     8.37   流入   2&#10;8    09:30:41    11 16.72     1.84   流出   1&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;函数代码文件：&#10;&lt;a class="link" href="http://yishuo.org/wp-content/uploads/2011/05/get.historydata.txt" target="_blank" rel="noopener"&#10; &gt;get.historydata&lt;/a&gt;&#10;&lt;a class="link" href="http://yishuo.org/wp-content/uploads/2011/05/get.nowdata.txt" target="_blank" rel="noopener"&#10; &gt;get.nowdata&lt;/a&gt;&lt;/p&gt;&#10;</description></item><item><title>R获取股票数据</title><link>https://gewutang.cn/2011/04/14/use-r-to-get-trading-data/</link><pubDate>Thu, 14 Apr 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/04/14/use-r-to-get-trading-data/</guid><description>&lt;p&gt;R中有多个包都提供了从线上数据库获取股票数据的方法。如果非得在其中找出一个最好的，quantmod当之无愧。譬如下载沪市大盘数据，代码可以是：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(quantmod) &#10;SSE &amp;lt;- getSymbols(&amp;quot;000001.SS&amp;quot;,auto.assign=FALSE) &#10;head(SSE) &#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;或者：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(quantmod) &#10;setSymbolLookup(SSE=list(name=&amp;quot;000001.SS&amp;quot;, src=&amp;quot;yahoo&amp;quot;)) &#10;getSymbols(&amp;quot;SSE&amp;quot;) &#10;head(SSE) &#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;以上是Jeff Ryan（quantmod作者）推荐过的方法。不过，后来JoshuaUlrich在他的邮件中给出了一个更简洁的方法：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(quantmod) &#10;getSymbols(&amp;quot;^SSEC&amp;quot;) &#10;head(SSEC) &#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;虽然quantmod的包出自Jeff Ryan之手，显而易见，在这一点上Joshua Ulrich是青出于蓝而胜于蓝。&lt;/p&gt;&#10;</description></item><item><title>quantmod：R中的金融分析包</title><link>https://gewutang.cn/2011/04/10/notes-about-quantmod/</link><pubDate>Sun, 10 Apr 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/04/10/notes-about-quantmod/</guid><description>&lt;p&gt;大概两年前，写了一份quantmod的读书笔记。当时只是草草完成，不足之处很多。于是，一直以来都有修缮之心，思忖良久，前段时间终于开始着手，目前大致确定了内容。先将完成的部分记在&lt;a class="link" href="https://github.com/dengyishuo/Notes/tree/master/quantmod" target="_blank" rel="noopener"&#10; &gt;这里&lt;/a&gt;。&lt;/p&gt;&#10;</description></item><item><title>用R拟合Vasicek模型</title><link>https://gewutang.cn/2011/04/10/use-r-to-fit-vasicek-model/</link><pubDate>Sun, 10 Apr 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/04/10/use-r-to-fit-vasicek-model/</guid><description>&lt;p&gt;Vasicek模型几乎可以说是最常见的利率模型。在金融领域有着很大的用处，可以用R来做Vasicek模型的人显然不够多。&lt;/p&gt;&#10;&lt;p&gt;这里给出一个拟合Vasicek模型的代码：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;#Vasicek negloglike函数:&#10;VASICEKnegloglike&amp;lt;-function(param,data,times){ n.obs&amp;lt;-length(data)&#10; dum&amp;lt;-sort.list(times)&#10; data&amp;lt;-data[dum]&#10; times&amp;lt;-times[dum]&#10; delta&amp;lt;-diff(times,1)&#10; mv&amp;lt;-data[1:(n.obs-1)]*exp(-param[2]*delta)+param[1]*(1-exp(-param[2]*delta))&#10; variance&amp;lt;-param[3]^2*(1-exp(-2*param[2]*delta))/(2*param[2])&#10; VASICEKnegloglike&amp;lt;--sum(log(dnorm(data[2:n.obs],mv,sqrt(variance))))/n.obs&#10;}&#10;&#10;# VASICEKyield函数&#10;VASICEKyield&amp;lt;-function(r,tau,Pparam,riskpremium=0)&#10;{ b&amp;lt;-Pparam[1]+riskpremium&#10; a&amp;lt;-Pparam[2]&#10; sig&amp;lt;-Pparam[3]&#10; Btau&amp;lt;-(1-exp(-a*tau))/a&#10; Atau&amp;lt;-((Btau-tau)*(a^2*b-0.5*sig^2)/a^2 - sig^2*Btau^2/(4*a))&#10; VASICEKyield&amp;lt;-r*Btau/tau-Atau/tau&#10;}&#10;&#10;# 数据实例&#10;maturities&amp;lt;-c(0.25,0.5,1,2,5,10)&#10;spliceddata&amp;lt;-matrix(scan(&amp;quot;http://www.math.ku.dk/~rolf/teaching/mfe04/USrates.52to04.dat&amp;quot;),byrow=T,ncol=7)&#10;obs&amp;lt;-spliceddata[,2]&#10;N&amp;lt;-length(obs)-1&#10;dt&amp;lt;-1/12&#10;data&amp;lt;-obs[2:(N+1)]&#10;lagdata&amp;lt;-obs[1:N]&#10;dates&amp;lt;-spliceddata[,1]&#10;&#10;#Closed form estimators&#10;bhat&amp;lt;-(sum(data*lagdata) - sum(data)*sum(lagdata)/N)/(sum(lagdata*lagdata) - sum(lagdata)*sum(lagdata)/N)&#10;kappahat&amp;lt;--log(bhat)/dt&#10;ahat&amp;lt;-sum(data)/N-bhat*sum(lagdata)/N&#10;thetahat&amp;lt;-ahat/(1-bhat)&#10;s2hat&amp;lt;-sum((data-lagdata*bhat-ahat)^2)/N&#10;sigmahat&amp;lt;-sqrt(2*kappahat*s2hat/(1-bhat^2))&#10;#plot the data (or more accurately, the short rate)&#10;plot(dates[2:(N+1)],data,type='l', xlab=&amp;quot;date&amp;quot;, ylab=&amp;quot;US 3M rate&amp;quot;, main=&amp;quot;US short rate 1952-2004&amp;quot;)&#10;abline(h=thetahat, lty=3)&#10;text(dates[10], thetahat, &amp;quot;thetahat&amp;quot;)&#10;&#10;tstVAS&amp;lt;-optim(par=c(thetahat,kappahat,sigmahat),&#10; fn=VASICEKnegloglike,method = &amp;quot;BFGS&amp;quot;, data=obs,times=dates)&#10;#analyze average yield curves&#10;meanyield&amp;lt;-2:7&#10;for(i in 1:6) meanyield[i]&amp;lt;-mean(spliceddata[,i+1])&#10;plot(maturities,meanyield,type='l',ylim=c(0.05,0.068),xlim=c(0,14),&#10; ylab=&amp;quot;mean/average/typical yield&amp;quot;,&#10;&#9; main=&amp;quot;Typical yield curves w/ US 1952-2004 data&amp;quot;)&#10;text(maturities[6],meanyield[6], &amp;quot;Average observed yield curve&amp;quot;)&#10;points(maturities,VASICEKyield(meanyield[1],maturities,tstVAS$par,riskpremium=0),type='l',lty=2)&#10;text(maturities[6],VASICEKyield(meanyield[1],maturities[6],tstVAS$par,riskpremium=0)+0.001,&#10; &amp;quot;Typical Vasicek model curve, I (r0 = avr. short rate, risk premium=0) &amp;quot;)&#10;points(maturities,VASICEKyield(thetahat,maturities,tstVAS$par,riskpremium=0),type='l',lty=2)&#10;text(maturities[6],VASICEKyield(thetahat,maturities[6],tstVAS$par,riskpremium=0)-0.0005,&amp;quot;Typical Vasicek model curve, II (r0 = thetahat, risk premium=0) &amp;quot;)&#10;&#10;rpfit&amp;lt;-function(rp){&#10;rpfit&amp;lt;-sum(abs(meanyield-VASICEKyield(meanyield[1],maturities,tstVAS$par,riskpremium=rp)))&#10;}&#10;&#10;rp&amp;lt;-optim(par=c(0),fn=rpfit,method = &amp;quot;BFGS&amp;quot;)$par&#10;&#10;theory&amp;lt;-VASICEKyield(meanyield[1],maturities,tstVAS$par,riskpremium=rp)&#10;points(maturities,theory,type='l',lty=2)&#10;&#10;text(maturities[6],theory[6],&amp;quot;Typical Vasicek model curve, III (r0=avr. short rate, risk premium='what fits best') &amp;quot;)&#10;&#10;plot(maturities,spliceddata[(N+1),2:7],type='l',ylab=&amp;quot;yield&amp;quot;,ylim=c(0.01,0.06),xlim=c(0,13), main=&amp;quot;On the last day in the sample&amp;quot;)&#10;&#10;text(maturities[6],spliceddata[(N+1),7], &amp;quot;Observed yield curve&amp;quot;)&#10;&#10;points(maturities,VASICEKyield(spliceddata[(N+1),3],maturities,tstVAS$par,riskpremium=rp),type='l',lty=2)&#10;&#10;text(maturities[6],VASICEKyield(spliceddata[(N+1),3],maturities[6],tstVAS$par,riskpremium=rp),&amp;quot;Vasicek model 'prediction' (w/ all the estimates) &amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>从Tsay的书看R的未来</title><link>https://gewutang.cn/2011/04/09/predict-r-based-on-the-change-of-tsays-book/</link><pubDate>Sat, 09 Apr 2011 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2011/04/09/predict-r-based-on-the-change-of-tsays-book/</guid><description>&lt;p&gt;&lt;a class="link" href="http://faculty.chicagobooth.edu/ruey.tsay/" target="_blank" rel="noopener"&#10; &gt;Tsay&lt;/a&gt;写的最著名的书叫&lt;a class="link" href="http://faculty.chicagobooth.edu/ruey.tsay/teaching/" target="_blank" rel="noopener"&#10; &gt;《Analysis of Financial Time Series》&lt;/a&gt;，这本书目前已经到了第三版。可能很少有人注意到，第三版跟第二版比在书籍介绍里有一个微妙的变化：&lt;/p&gt;&#10;&lt;p&gt;第二版的部分&lt;a class="link" href="http://faculty.chicagobooth.edu/ruey.tsay/teaching/fts2/" target="_blank" rel="noopener"&#10; &gt;书籍介绍&lt;/a&gt;如下：&#10;Software packages used in the book:&#10;SCA (Scientific Computing Associates),&#10;S-Plus with FinMetrics (Insightful)&#10;RATS (Regression Analysis of Time Series),&#10;&lt;strong&gt;and&lt;/strong&gt;&#10;** R with RMetrics (newer version is recommended.)**&#10;Instructions and some demonstrations for using R and S-Plus&#10;can be found in my teaching web: R-demo&lt;/p&gt;&#10;&lt;p&gt;第三版的部分&lt;a class="link" href="http://faculty.chicagobooth.edu/ruey.tsay/teaching/fts3/" target="_blank" rel="noopener"&#10; &gt;书籍介绍&lt;/a&gt;如下：&#10;&lt;strong&gt;The main software package used in the book is R:&lt;/strong&gt;&#10;Other packages used are&#10;SCA (Scientific Computing Associates),&#10;S-Plus with FinMetrics (Insightful)&#10;RATS (Regression Analysis of Time Series).&lt;/p&gt;&#10;&lt;p&gt;Further Instructions and some demonstrations for using R and S-Plus&#10;can be found in my teaching web for Business 41202.&lt;/p&gt;&#10;&lt;p&gt;R从第二版屈居单词“and”之后，变成第三版“main software package”，我想这个变化再次印证了R的潜力。&lt;/p&gt;&#10;</description></item><item><title>scatterplot3d:一个特立独行的R包</title><link>https://gewutang.cn/2010/06/13/scatterplot3d/</link><pubDate>Sun, 13 Jun 2010 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2010/06/13/scatterplot3d/</guid><description>&lt;p&gt;scatterplot3d是一个力图在3D空间展示多维数据的R包，在这个包里只含有一个函数scatterplot3d()，这一点上可谓是特立独行。scatterplot3d()的用法如下：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; scatterplot3d(x, y=NULL, z=NULL, color=par(&amp;quot;col&amp;quot;), pch=NULL,&#10; main=NULL, sub=NULL, xlim=NULL, ylim=NULL, zlim=NULL,&#10; xlab=NULL, ylab=NULL, zlab=NULL, scale.y=1, angle=40,&#10; axis=TRUE, tick.marks=TRUE, label.tick.marks=TRUE,&#10; x.ticklabs=NULL, y.ticklabs=NULL, z.ticklabs=NULL,&#10; y.margin.add=0, grid=TRUE, box=TRUE, lab=par(&amp;quot;lab&amp;quot;),&#10; lab.z=mean(lab[1:2]), type=&amp;quot;p&amp;quot;, highlight.3d=FALSE,&#10; mar=c(5,3,4,3)+0.1, col.axis=par(&amp;quot;col.axis&amp;quot;),&#10; col.grid=&amp;quot;grey&amp;quot;, col.lab=par(&amp;quot;col.lab&amp;quot;),&#10; cex.symbols=par(&amp;quot;cex&amp;quot;), cex.axis=0.8 * par(&amp;quot;cex.axis&amp;quot;),&#10; cex.lab=par(&amp;quot;cex.lab&amp;quot;), font.axis=par(&amp;quot;font.axis&amp;quot;),&#10; font.lab=par(&amp;quot;font.lab&amp;quot;), lty.axis=par(&amp;quot;lty&amp;quot;),&#10; lty.grid=par(&amp;quot;lty&amp;quot;), lty.hide=NULL, lty.hplot=par(&amp;quot;lty&amp;quot;),&#10; log=&amp;quot;&amp;quot;, ...)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;这个函数的参数多到让人眼花缭乱。下面是几个例子:&lt;/p&gt;&#10;&lt;p&gt;先用scatterplot3d()画一个螺旋线：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(scatterplot3d)&#10;z &amp;lt;- seq(-10, 10, 0.01)&#10;x &amp;lt;- cos(z)&#10;y &amp;lt;- sin(z)&#10;scatterplot3d(x, y, z, highlight.3d=TRUE, col.axis=&amp;quot;blue&amp;quot;,col.grid=&amp;quot;lightblue&amp;quot;,main=&amp;quot;scatterplot3d - 1&amp;quot;, pch=20)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/06/13/scatterplot3d/index_files/figure-html/unnamed-chunk-2-1.png" width="672" /&gt;&#10;&lt;p&gt;再画半椭圆:&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;temp&amp;lt;- seq(-pi, 0, length = 50)&#10;x &amp;lt;- c(rep(1, 50) %*% t(cos(temp)))&#10;y &amp;lt;- c(cos(temp) %*% t(sin(temp)))&#10;z &amp;lt;- c(sin(temp) %*% t(sin(temp)))&#10;scatterplot3d(x, y, z, highlight.3d=TRUE,col.axis=&amp;quot;blue&amp;quot;, col.grid=&amp;quot;lightblue&amp;quot;,main=&amp;quot;scatterplot3d - 2&amp;quot;, pch=20)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/06/13/scatterplot3d/index_files/figure-html/unnamed-chunk-3-1.png" width="672" /&gt;&#10;&lt;p&gt;将两者结合，输出结果很像龙盘柱。有点酷！&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; x &amp;lt;- c(rep(1, 50) %*% t(cos(temp)))&#10; y &amp;lt;- c(cos(temp) %*% t(sin(temp)))&#10; z &amp;lt;- 10 * c(sin(temp) %*% t(sin(temp)))&#10; color &amp;lt;- rep(&amp;quot;green&amp;quot;, length(x))&#10; temp &amp;lt;- seq(-10, 10, 0.01)&#10; x &amp;lt;- c(x, cos(temp))&#10; y &amp;lt;- c(y, sin(temp))&#10; z &amp;lt;- c(z, temp)&#10; color &amp;lt;- c(color, rep(&amp;quot;red&amp;quot;, length(temp)))&#10; scatterplot3d(x, y, z, color, pch=20, zlim=c(-2, 10),main=&amp;quot;scatterplot3d - 3&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/06/13/scatterplot3d/index_files/figure-html/unnamed-chunk-4-1.png" width="672" /&gt;&#10;&lt;p&gt;来一个比较庸俗的，三维bar图：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;my.mat &amp;lt;- matrix(runif(25), nrow=5)&#10;dimnames(my.mat) &amp;lt;- list(LETTERS[1:5], letters[11:15])&#10;s3d.dat &amp;lt;- data.frame(cols=as.vector(col(my.mat)),rows=as.vector(row(my.mat)),value=as.vector(my.mat))&#10;scatterplot3d(s3d.dat, type=&amp;quot;h&amp;quot;, lwd=5, pch=&amp;quot; &amp;quot;,x.ticklabs=colnames(my.mat),y.ticklabs=rownames(my.mat))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/06/13/scatterplot3d/index_files/figure-html/unnamed-chunk-5-1.png" width="672" /&gt;&#10;&lt;p&gt;上面的可以说都不是很实用，下面看一下二维回归平面图：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;data(trees)&#10;s3d &amp;lt;- scatterplot3d(trees, type=&amp;quot;h&amp;quot;, highlight.3d=TRUE,angle=55, scale.y=0.7, pch=16, main=&amp;quot;scatterplot3d - 5&amp;quot;)&#10;s3d$points3d(seq(10,20,2), seq(85,60,-5), seq(60,10,-10),col=&amp;quot;blue&amp;quot;, type=&amp;quot;h&amp;quot;, pch=16)&#10; # 画回归平面&#10;attach(trees)&#10;my.lm &amp;lt;- lm(Volume ~ Girth + Height)&#10;s3d$plane3d(my.lm, lty.box = &amp;quot;solid&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/06/13/scatterplot3d/index_files/figure-html/unnamed-chunk-6-1.png" width="672" /&gt;&#10;&lt;p&gt;我看见有很多帖子索要二维正态分布的示意图，这里画一个，&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; library(mvtnorm)&#10; x1 &amp;lt;- seq(-10, 10, length = 51)&#10; x2 &amp;lt;- seq(-10, 10, length = 51)&#10; dens &amp;lt;- matrix(dmvnorm(expand.grid(x1,x2),sigma=rbind(c(3,2),c(2,3))),ncol=length(x1))&#10; s3d&amp;lt;-scatterplot3d(x1,x2,seq(min(dens),max(dens),length=length(x1)),&#10; type=&amp;quot;n&amp;quot;,grid=FALSE,angle = 70,&#10; zlab=expression(f(x[1],x[2])),&#10; xlab=expression(x[1]),ylab=expression(x[2]),&#10; main=&amp;quot;Bivariate normal distribution&amp;quot;)&#10; text(s3d$xyz.convert(-1,10,0.07),&#10; labels=expression(f(x)==frac(1,sqrt((2*pi)^n*phantom(&amp;quot;.&amp;quot;)*det(Sigma[X])))*phantom(&amp;quot;.&amp;quot;)*exp(bgroup(&amp;quot;(&amp;quot;,-scriptstyle(frac(1,2)*phantom(&amp;quot;.&amp;quot;))*(x-mu)^T*Sigma[X]^-1*(x-mu),&amp;quot;)&amp;quot;))))&#10; for(i in length(x1):1)&#10; s3d$points3d(rep(x1[i], length(x2)), x2, dens[i,], type = &amp;quot;l&amp;quot;)&#10; for(i in length(x2):1)&#10; s3d$points3d(x1, rep(x2[i], length(x1)), dens[,i], type = &amp;quot;l&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/06/13/scatterplot3d/index_files/figure-html/unnamed-chunk-7-1.png" width="672" /&gt;&#10;&lt;p&gt;之所以画下面这个，完全是因为我贪图色彩：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; cubedraw &amp;lt;- function(res3d, min = 0, max = 255, cex = 2, text. = FALSE)&#10; {&#10; cube01 &amp;lt;- rbind(c(0,0,1), 0, c(1,0,0), c(1,1,0), 1, c(0,1,1), # &amp;lt; 6 outer&#10; c(1,0,1), c(0,1,0)) &#10; cub &amp;lt;- min + (max-min)* cube01&#10; res3d$points3d(cub[c(1:6,1,7,3,7,5) ,], cex = cex, type = 'b', lty = 1)&#10; res3d$points3d(cub[c(2,8,4,8,6), ], cex = cex, type = 'b', lty = 3)&#10; if(text.)&#10; text(res3d$xyz.convert(cub), labels=1:nrow(cub), col='tomato', cex=2)&#10; }&#10; cc &amp;lt;- colors()&#10; crgb &amp;lt;- t(col2rgb(cc))&#10; par(xpd = TRUE)&#10; rr &amp;lt;- scatterplot3d(crgb, color = cc, box = FALSE, angle = 24,&#10; xlim = c(-50, 300), ylim = c(-50, 300), zlim = c(-50, 300))&#10; cubedraw(rr)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/06/13/scatterplot3d/index_files/figure-html/unnamed-chunk-8-1.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt; rbc &amp;lt;- rainbow(201)&#10; Rrb &amp;lt;- t(col2rgb(rbc))&#10; rR &amp;lt;- scatterplot3d(Rrb, color = rbc, box = FALSE, angle = 24,&#10; xlim = c(-50, 300), ylim = c(-50, 300), zlim = c(-50, 300))&#10; cubedraw(rR)&#10; rR$points3d(Rrb, col = rbc, pch = 16)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/06/13/scatterplot3d/index_files/figure-html/unnamed-chunk-8-2.png" width="672" /&gt;&#10;</description></item><item><title>支持向量机</title><link>https://gewutang.cn/2010/05/05/support-vector-machine/</link><pubDate>Wed, 05 May 2010 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2010/05/05/support-vector-machine/</guid><description>&lt;p&gt;支持向量机(Support Vector Machine,SVM)是Corinna Cortes和Vapnik等于1995年首先提出的一种机器学习方法，它在解决小样本、非线性及高维模式识别中表现出许多特有的优势，并能够推广应用到函数拟合等 其他机器学习问题中。&lt;/p&gt;&#10;&lt;p&gt;通俗的介绍一下这个过程:&lt;/p&gt;&#10;&lt;p&gt;我们有一些数据点，这些数据点是n维实空间中的点。我们希望能够把这些点通过一个n-1维的超平面分开。通常这个被称为线性分类器。有很多分类器都符合这个要求。但是我们还希望找到分类最佳的平面，即使得属 于两个不同类的数据点间隔最大的那个面，该面亦称为最大间隔超平面。如果我们能够找到这个面，那么这个分类器就称为最大间隔分类器。&lt;/p&gt;&#10;&lt;p&gt;理解了上面这段话就可以理解支持向量机了。支持向量机是将向量映射到一个更高维的空间里，在这个空间里建立有一个最大间隔超平面。在分开数据的超平面的两边建有两个互相平行的超平面。建立方向合适的分隔超平面使两个与之平行的超平面间的距离最大化。其假定为，平行超平面间的距离或差距越大，分类器的总误差越小。而所谓支持向量是指那些在间隔区边缘的训练样本点。这里的“机（machine,机器）”实际上是一个算法。在机器学习领域，常把一些算法看做是一个机器。&lt;/p&gt;&#10;&lt;p&gt;学习支持向量机知识的一个极好指南是C.J.CBurges的《模式识别支持向量机指南》。&lt;/p&gt;&#10;&lt;p&gt;目前，R中已经实现了支持向量机算法(相关的包有e1071包、kernlab包、klar包和svmpath包。以数据iris和cats为例加以说明：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;library(e1071)&#10;library(MASS)&#10;data(cats)&#10;m= svm(Sex~., data = cats)&#10;plot(m, cats)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/05/05/support-vector-machine/index_files/figure-html/unnamed-chunk-1-1.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;data(iris)&#10;m2=svm(Species~., data = iris)&#10;plot(m2, iris, Petal.Width ~ Petal.Length, slice = list(Sepal.Width = 3, Sepal.Length = 4))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/05/05/support-vector-machine/index_files/figure-html/unnamed-chunk-2-1.png" width="672" /&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;plot(m, cats, svSymbol = 1, dataSymbol = 2, symbolPalette = rainbow(4),color.palette =terrain.colors)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;img src="https://gewutang.cn/2010/05/05/support-vector-machine/index_files/figure-html/unnamed-chunk-2-2.png" width="672" /&gt;&#10;&lt;p&gt;支持向量机还可以用到股票价格的预测上，具体案例回头再写。&lt;/p&gt;&#10;</description></item><item><title>BEKK模型</title><link>https://gewutang.cn/2010/04/15/about-bekk-model/</link><pubDate>Thu, 15 Apr 2010 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2010/04/15/about-bekk-model/</guid><description>&lt;p&gt;BEKK模型是目前比较流行的多变量波动性模型，可以看作GARCH模型在多维空间的实现。BEKK模型在应用过程中也有诸多缺点，其中最大的一个不足之处在于模型的待估计参数会随着模型维数的增加指数型增长。然而，这一点肯定会随着计算机的发展而被逐渐克服的。&lt;/p&gt;&#10;&lt;p&gt;R软件中提供了mgarch和mgarchBEKK两个包来估计BEKK模型参数。&lt;/p&gt;&#10;&lt;h2 id="mgarch包及其示例"&gt;&lt;a href="#mgarch%e5%8c%85%e5%8f%8a%e5%85%b6%e7%a4%ba%e4%be%8b" class="header-anchor"&gt;&lt;/a&gt;mgarch包及其示例&#10;&lt;/h2&gt;&lt;pre&gt;&lt;code class="language-r"&gt;# 安装包（如果未安装）&#10;# devtools::install_github(&amp;quot;https://github.com/vst/mgarch&amp;quot;)&#10;&#10;library(mgarch)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：tseries&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Registered S3 method overwritten by 'quantmod':&#10;## method from&#10;## as.zoo.data.frame zoo&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## 载入需要的程序包：mvtnorm&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;先看mgarch包，该包有三个主要函数：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;mvBEKK.sim: 模拟一个MGARCH-BEKK过程&lt;/li&gt;&#10;&lt;li&gt;mvBEKK.est: 估计MGARCH-BEKK模型的参数&lt;/li&gt;&#10;&lt;li&gt;mvBEKK.diag:对拟合的MGARCH-BEKK模型进行诊断&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;可以通过以下命令查询相关函数的用法：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;?mvBEKK.sim&#10;?mvBEKK.est&#10;?mvBEKK.diag&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;运行以下命令可以模拟一个MGARCH-BEKK过程：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;set.seed(123)&#10;sim = mvBEKK.sim(series.count = 3, T = 1000)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Class attributes are accessible through following names:&#10;## length series.count order params true.params eigenvalues uncond.cov.matrix white.noise eps cor sd&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;合并模拟的时间序列：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;eps = data.frame(sim$eps[[1]], sim$eps[[2]], sim$eps[[3]]) &#10;head(eps)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## sim.eps..1.. sim.eps..2.. sim.eps..3..&#10;## 1 0.9472441 1.2177306 0.5491724&#10;## 2 -1.1241768 -0.3366113 -0.6261458&#10;## 3 0.7179649 -0.3272567 1.6880032&#10;## 4 -0.4857962 1.2230006 -1.9563961&#10;## 5 -1.1301479 4.0603942 -1.3856283&#10;## 6 0.2057734 1.1435079 -0.6392246&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;tail(eps)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## sim.eps..1.. sim.eps..2.. sim.eps..3..&#10;## 995 -1.43678861 -0.8651118 -1.55380698&#10;## 996 -1.10173653 -0.5863329 -1.14479754&#10;## 997 -1.06902893 -0.4398771 -3.08558958&#10;## 998 -0.11478218 0.7226409 -3.00375826&#10;## 999 -1.18562636 2.4487154 -0.04579639&#10;## 1000 0.05764529 -0.2241948 0.86390660&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;估计模型参数：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;est &amp;lt;- mvBEKK.est(eps)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Warning in mvBEKK.est(eps): negative inverted hessian matrix element&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;查看估计结果包含哪些信息：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;names(est)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## [1] &amp;quot;eps&amp;quot; &amp;quot;series.length&amp;quot; &amp;quot;estimation.time&amp;quot; &#10;## [4] &amp;quot;total.time&amp;quot; &amp;quot;order&amp;quot; &amp;quot;estimation&amp;quot; &#10;## [7] &amp;quot;aic&amp;quot; &amp;quot;asy.se.coef&amp;quot; &amp;quot;est.params&amp;quot; &#10;## [10] &amp;quot;cor&amp;quot; &amp;quot;sd&amp;quot; &amp;quot;H.estimated&amp;quot; &#10;## [13] &amp;quot;eigenvalues&amp;quot; &amp;quot;uncond.cov.matrix&amp;quot; &amp;quot;residuals&amp;quot;&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;p&gt;模型诊断：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;mvBEKK.diag(est)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#9;Number of estimated series : 3 &#10;## &#9;Length of estimated series : 1000 &#10;## &#9;Estimation Time : 32.41842 &#10;## &#9;Total Time : 32.98894 &#10;## &#9;BEKK order : 1 1 &#10;## &#9;Eigenvalues : 0.8982855 0.5101535 0.4535976 0.3020472 0.2611067 0.2258987 0.1373383 0.05469751 0.05280793 &#10;## &#9;aic : 4163.509 &#10;## &#9;unconditional cov. matrix : 2.654942 -0.4582163 0.8566066 -0.4582163 2.38067 0.1093766 0.8566066 0.1093766 2.01 &#10;## &#9;var(resid 1 ) : 0.999399 &#10;## &#9;mean(resid 1 ) : -0.03860414 &#10;## &#9;var(resid 2 ) : 0.9988757 &#10;## &#9;mean(resid 2 ) : 0.04335019 &#10;## &#9;var(resid 3 ) : 0.997348 &#10;## &#9;mean(resid 3 ) : 0.02152967 &#10;## &#9;Estimated parameters :&#10;## &#10;## &#9;C estimates:&#10;## [,1] [,2] [,3]&#10;## [1,] 0.8909642 0.3328637 0.34152387&#10;## [2,] 0.0000000 0.9827892 0.05270326&#10;## [3,] 0.0000000 0.0000000 1.01236445&#10;## &#10;## &#9;ARCH estimates:&#10;## [,1] [,2] [,3]&#10;## [1,] 0.340809760 0.06992293 0.07918491&#10;## [2,] -0.064873614 0.36049917 0.35553210&#10;## [3,] -0.008381618 -0.06665216 0.50150310&#10;## &#10;## &#9;GARCH estimates:&#10;## [,1] [,2] [,3]&#10;## [1,] -0.3353086 0.37376137 -0.5032390&#10;## [2,] 0.2151724 0.03756262 0.4608374&#10;## [3,] 0.1756196 0.01577004 -0.4594647&#10;## &#10;## &#9;asy.se.coef : &#10;## &#10;## &#9;C estimates, standard errors:&#10;## [,1] [,2] [,3]&#10;## [1,] 0.07738385 0.1351731 0.2359051&#10;## [2,] 0.00000000 0.1141723 0.2671477&#10;## [3,] 0.00000000 0.0000000 0.2311768&#10;## &#10;## &#9;ARCH estimates, standard errors:&#10;## [,1] [,2] [,3]&#10;## [1,] 0.05481912 0.05484527 0.07796872&#10;## [2,] 0.04677913 0.05338068 0.07267995&#10;## [3,] 0.02304154 0.02555282 0.04677987&#10;## &#10;## &#9;GARCH estimates, standard errors:&#10;## [,1] [,2] [,3]&#10;## [1,] 0.17105425 0.19123870 0.31018515&#10;## [2,] 0.17509179 0.26972309 0.33665408&#10;## [3,] 0.05380941 0.07028591 0.09210273&#10;## Called from: mvBEKK.diag(est)&#10;## debug: for (i in 1:length(estimation$eps)) {&#10;## plot(estimation$residuals[[i]])&#10;## browser()&#10;## dev.off()&#10;## }&#10;## debug: plot(estimation$residuals[[i]])&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## debug: browser()&#10;## debug: dev.off()&#10;## debug: plot(estimation$residuals[[i]])&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## debug: browser()&#10;## debug: dev.off()&#10;## debug: plot(estimation$residuals[[i]])&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## debug: browser()&#10;## debug: dev.off()&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;h2 id="mgarchbekk包及其示例"&gt;&lt;a href="#mgarchbekk%e5%8c%85%e5%8f%8a%e5%85%b6%e7%a4%ba%e4%be%8b" class="header-anchor"&gt;&lt;/a&gt;mgarchBEKK包及其示例&#10;&lt;/h2&gt;&lt;pre&gt;&lt;code class="language-r"&gt;# 安装包（如未安装）&#10;# devtools::install_github(&amp;quot;https://github.com/vst/mgarchBEKK&amp;quot;)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 加载包&#10;library(mgarchBEKK)&#10;# 模拟mgarchBEKK过程&#10;simulated &amp;lt;- simulateBEKK(2, 1000, c(1,1))&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Class attributes are accessible through following names:&#10;## length series.count order params true.params eigenvalues uncond.cov.matrix white.noise eps cor sd&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 合并模拟数据&#10;simulated &amp;lt;- do.call(cbind, simulated$eps)&#10;# 估计模型&#10;estimated &amp;lt;- BEKK(simulated)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;## H IS SINGULAR!...&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Warning in BEKK(simulated): negative inverted hessian matrix element&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 模型诊断&#10;diagnoseBEKK(estimated)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## &#9;Number of estimated series : 2000 &#10;## &#9;Length of estimated series : 1000 &#10;## &#9;Estimation Time : 3.208226 &#10;## &#9;Total Time : 3.330154 &#10;## &#9;BEKK order : 1 1 &#10;## &#9;Eigenvalues : 0.7940983 0.7122278 0.5839173 0.5353965 &#10;## &#9;aic : 4614.775 &#10;## &#9;unconditional cov. matrix : 6.481396 1.496551 1.496551 7.939293 &#10;## &#9;var(resid 1 ) : 1.000363 &#10;## &#9;mean(resid 1 ) : -0.007109519 &#10;## &#9;var(resid 2 ) : 0.9958192 &#10;## &#9;mean(resid 2 ) : -0.01444951 &#10;## &#9;Estimated parameters :&#10;## &#10;## &#9;C estimates:&#10;## [,1] [,2]&#10;## [1,] 0.9304752 0.4214324&#10;## [2,] 0.0000000 1.6921455&#10;## &#10;## &#9;ARCH estimates:&#10;## [,1] [,2]&#10;## [1,] -0.5382996 0.003724502&#10;## [2,] 0.3896205 -0.351431137&#10;## &#10;## &#9;GARCH estimates:&#10;## [,1] [,2]&#10;## [1,] 0.3804035 0.5270529&#10;## [2,] -0.2806881 0.6526116&#10;## &#10;## &#9;asy.se.coef : &#10;## &#10;## &#9;C estimates, standard errors:&#10;## [,1] [,2]&#10;## [1,] 0.2069876 0.5373757&#10;## [2,] 0.0000000 0.2889314&#10;## &#10;## &#9;ARCH estimates, standard errors:&#10;## [,1] [,2]&#10;## [1,] 0.04044854 0.04641720&#10;## [2,] 0.02825686 0.04050683&#10;## &#10;## &#9;GARCH estimates, standard errors:&#10;## [,1] [,2]&#10;## [1,] 0.05265359 0.05895967&#10;## [2,] 0.06856104 0.07941475&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## Called from: diagnoseBEKK(estimated)&#10;## debug: dev.off()&#10;## debug: plot(estimation$residuals[[i]])&#10;&lt;/code&gt;&lt;/pre&gt;&#10;&lt;pre&gt;&lt;code&gt;## debug: browser()&#10;## debug: dev.off()&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item><item><title>四龟追逐问题</title><link>https://gewutang.cn/2010/03/29/four-turtles/</link><pubDate>Mon, 29 Mar 2010 00:00:00 +0000</pubDate><guid>https://gewutang.cn/2010/03/29/four-turtles/</guid><description>&lt;p&gt;四龟行走是一个很著名的论题，题目的大意是这样的：&lt;/p&gt;&#10;&#10; &lt;blockquote&gt;&#10; &lt;p&gt;在一个房间的四个角上，分别有一只乌龟。在某一个时刻t同时出发以匀速V走向顺时针方向的下一只乌龟，如果他们的方向始终对准目标，那么它们的运动轨迹是怎样的？&lt;/p&gt;&#10;&#10; &lt;/blockquote&gt;&#10;&lt;p&gt;这道题目的解答方法至少有三个：&lt;/p&gt;&#10;&lt;ul&gt;&#10;&lt;li&gt;借助微分方程来解答，这是最正经的解法，但是也最没有意思，是&amp;quot;书虫&amp;quot;才干的出来的事情。&lt;/li&gt;&#10;&lt;li&gt;常理判断。由于四龟地位完全对称，而相邻两龟运动方向始终垂直，因此四龟轨迹对称且都是螺旋线。这是极其聪明的人才能干出的事情。&lt;/li&gt;&#10;&lt;li&gt;统计模拟方法。这个方法兼具艺术性和趣味性，而且不会远离群众，是有趣的人会干出的事情。&lt;/li&gt;&#10;&lt;/ul&gt;&#10;&lt;p&gt;关于前两个这里一笔带过，第三个方法在薛毅很久之前的一本书《统计建模与R软件》是有提及过。怡轩说，这个统计模拟的例子于他有着特殊的意义。巧合的是，四龟行走也恰恰是我学习统计学的启蒙案例。也就是在见到这个例子的刹那，我才初次领悟了编程的景致之所在，也开始了对编程的敬仰之旅。&lt;/p&gt;&#10;&lt;p&gt;前段时间，在看自然图形时，突然发现自然界很多植物如“紫荆花”等等都有着类似四龟行走轨迹的花型。因此萌发妄想将它写成一个动画。我尽量避免使用复杂的数学语言来描述以上过程，因为我觉得数学语言尽管清晰有时候只会耽误大众对事情本质的理解。&lt;/p&gt;&#10;&lt;p&gt;下面是一段模拟四龟行走问题的R代码：&lt;/p&gt;&#10;&lt;pre&gt;&lt;code class="language-r"&gt;# 加载必要的包&#10;library(ggplot2)&#10;library(gganimate)&#10;&#10;# 模拟参数设置&#10;V &amp;lt;- 0.02 # 移动速度&#10;dt &amp;lt;- 0.01 # 时间步长&#10;total_time &amp;lt;- 500 # 总模拟时间&#10;threshold &amp;lt;- 0.01 # 停止阈值&#10;&#10;# 初始化四只乌龟的起始位置（正方形顶点）&#10;turtles &amp;lt;- matrix(c(&#10; 0.0, 1.0, # 左上角乌龟1&#10; 1.0, 1.0, # 右上角乌龟2&#10; 1.0, 0.0, # 右下角乌龟3&#10; 0.0, 0.0 # 左下角乌龟4&#10;), ncol = 2, byrow = TRUE)&#10;&#10;# 轨迹记录矩阵&#10;history &amp;lt;- data.frame(&#10; turtle = integer(),&#10; time = numeric(),&#10; x = numeric(),&#10; y = numeric()&#10;)&#10;&#10;# 主循环模拟&#10;current_time &amp;lt;- 0&#10;while(current_time &amp;lt; total_time) {&#10; # 计算各乌龟的目标方向&#10; new_positions &amp;lt;- matrix(nrow = 4, ncol = 2)&#10; &#10; for(i in 1:4) {&#10; current_pos &amp;lt;- turtles[i, ]&#10; target_pos &amp;lt;- turtles[(i %% 4) + 1, ]&#10; &#10; # 计算方向向量并标准化&#10; direction &amp;lt;- target_pos - current_pos&#10; distance &amp;lt;- sqrt(sum(direction^2))&#10; &#10; if(distance &amp;lt; threshold) break # 提前终止条件&#10; &#10; unit_direction &amp;lt;- direction / distance&#10; displacement &amp;lt;- V * dt * unit_direction&#10; &#10; new_positions[i, ] &amp;lt;- current_pos + displacement&#10; }&#10; &#10; # 记录当前时刻所有位置&#10; for(i in 1:4) {&#10; history &amp;lt;- rbind(history, data.frame(&#10; turtle = i,&#10; time = current_time,&#10; x = turtles[i, 1],&#10; y = turtles[i, 2]&#10; ))&#10; }&#10; &#10; # 同步更新所有乌龟位置&#10; turtles &amp;lt;- new_positions&#10; current_time &amp;lt;- current_time + dt&#10;}&#10;&#10;# 可视化静态轨迹&#10;ggplot(history, aes(x, y, color = factor(turtle))) +&#10; geom_path(aes(group = turtle), linewidth = 0.8) +&#10; geom_point(data = subset(history, time == min(time)), &#10; size = 4, shape = 19) + # 起始点&#10; geom_point(data = subset(history, time == max(time)), &#10; size = 4, shape = 4) + # 终止点&#10; scale_color_manual(values = c(&amp;quot;#FF6B6B&amp;quot;, &amp;quot;#4ECDC4&amp;quot;, &amp;quot;#45B7D1&amp;quot;, &amp;quot;#96CEB4&amp;quot;)) +&#10; coord_fixed() +&#10; theme_minimal() +&#10; labs(title = &amp;quot;四龟追逐运动轨迹&amp;quot;, color = &amp;quot;乌龟编号&amp;quot;)&#10;&#10;# 生成动态可视化（需要安装gganimate）&#10;anim &amp;lt;- ggplot(history, aes(x, y, color = factor(turtle))) +&#10; geom_path(aes(group = turtle), alpha = 0.5) +&#10; geom_point(size = 3) +&#10; transition_reveal(time) +&#10; scale_color_manual(values = c(&amp;quot;#FF6B6B&amp;quot;, &amp;quot;#4ECDC4&amp;quot;, &amp;quot;#45B7D1&amp;quot;, &amp;quot;#96CEB4&amp;quot;)) +&#10; coord_fixed() +&#10; labs(title = '时间: {frame_along}', x = 'X坐标', y = 'Y坐标', color = '乌龟编号')&#10;&#10;animate(anim, fps = 20, duration = total_time, width = 600, height = 600)&#10;&lt;/code&gt;&lt;/pre&gt;&#10;</description></item></channel></rss>