2008年12月5日星期五

Matlab使用经验

Matlab使用经验

这篇文章中将随时添加一些使用Matlab时别的地方不容易找到的问题的解决方法。




Matlab批处理方式运行

在用Matlab运行大任务时,为了避免终端断开造成的误退出,可以用批处理方式运行Matlab
写一个如下的名为batchmatlabshell脚本:

#/bin/sh
nohup matlab -nodisplay -nodesktop -nojvm -nosplash < $1 >& $2 &

设置好运行权限,如果有一个myprog.m要批运行的话,可用如下命令:

batchmatlab myprog.m myprog-log.txt

文本型的输出的结果将保存在文件“myprog-log.txt”中。批处理运行的Matlab程序如需绘图
应直接输出到文件中。




如何从文件中读入一系列文件名

其中假设list.txt中每行有一个文件名, 我们需要对这些文件作一些处理,代码例子如下
flist = readlist('list.txt');
nf = length(flist);
for ii = 1:nf;
fname = char(flist(ii));
%% Do something for file fname here.
end;
%%% Read a list of lines from a file.
function li=readlist(fname)
fid = fopen(fname, 'r');
li={};
ii=0;
while 1;
ii = ii+1;
tt = fgetl(fid);
if(~ischar(tt));
break;
end;
li(ii) = cellstr(tt);
end;
end
函数readlist把指定文件中的文件名表读入到结果li中,li是一个cell array,其中每一个元素是cell类型的字符串,为了使用其元素需要用char函数转换为character array类型。

Linux使用经验

Linux使用经验

本文总结一些使用Linux/Unix过程中积累的经验,随时添加。

批量修改文件属性


如果要把某目录adir中所有文件设为组可读写,可用
chmod -R g+rw adir
其中的-R选项是要求跟入子目录的意思。

为了把某共享目录asharedir中所有属于用户aus和组agrp的文件属性修改为组可读写,可用find命令:
find asharedir -u aus -g agrp -exec chmod g+rw {} ;
其中find命令首先指定查找的目录,然后指定匹配的条件,在-exec后指定找到的文件的操作,其中{}通配当前找到的文件,“ ;”作为-exec命令的结尾标志。

在某个目录中查找含有特定字符串的文件

find 目录名 -name "文件通配符" -exec grep -H "要查找的字符串" {} \;

其中双撇号和空格都是必须的。例如,要在当前目录中查找所有含有assist字符串的后缀为.r的文件,就可以用命令

find . -name "*.r" -exec grep -H "assist" {} \;

Emacs常用设置

Emacs常用设置

作者从网上发现了一些使用Emacs时经常需要的设置贴在这里备查。


MS Windows下使用注意事项

中文环境设置

;; for Chinese environment

(set-language-environment 'Chinese-GB)
;;(set-keyboard-coding-system 'chinese-iso-8bit-dos)
(set-keyboard-coding-system 'euc-cn)
(set-clipboard-coding-system 'euc-cn)
(set-terminal-coding-system 'euc-cn)
(set-buffer-file-coding-system 'euc-cn)
(set-selection-coding-system 'euc-cn)
(modify-coding-system-alist 'process "*" 'euc-cn)
(setq default-process-coding-system
'(euc-cn . euc-cn))
(setq-default pathname-coding-system 'euc-cn)

标记开始命令

在中文Windows中,Ctrl+Space已被用作切换输入法,不能再作为Emacs的标记切换命令,所以定义Ctrl+2作为标记切换命令。

;; for using C-2 as marking command
(global-set-key (quote [67108914]) (quote set-mark-command))

使用RCS进行版本控制

下载Windows用的RCS的执行文件放到Windows路径可以查到的地方,比如Emacs安装的执行文件目录bin。然后在控制面板-系统-高级-环境变量那里设置环境变量TZ(时区),如TZ=GMT8。




调用ESS编辑SAS, R程序

;; For R and SAS mode

(load "ess-site")


Python编辑模式

;; for python mode
(setq auto-mode-alist
(cons '("\\.py$" . python-mode) auto-mode-alist))
(setq interpreter-mode-alist
(cons '("python" . python-mode)
interpreter-mode-alist))
(autoload 'python-mode "python-mode" "Python editing mode." t)


Matlab编辑模式


;; for matlab mode
(add-to-list 'load-path "e:/matlab7/java/extern/EmacsLink/lisp")
(autoload 'matlab-eei-connect "matlab-eei"
"Connects Emacs to MATLAB's external editor interface.")

(autoload 'matlab-mode "matlab" "Enter Matlab mode." t)
(setq auto-mode-alist (cons '("\\.m\\'" . matlab-mode) auto-mode-alist))
(autoload 'matlab-shell "matlab" "Interactive Matlab mode." t)

(setq matlab-indent-function t) ; if you want function bodies indented
(setq matlab-verify-on-save-flag nil) ; turn off auto-verify on save
(defun my-matlab-mode-hook ()
(setq fill-column 76)
(imenu-add-to-menubar "Find")) ; where auto-fill should wrap
(add-hook 'matlab-mode-hook 'my-matlab-mode-hook)


RST文本编辑

;; For reStructuredText.
(require 'rst)
(add-hook 'text-mode-hook 'rst-text-mode-bindings)
(setq auto-mode-alist
(append '(("\\.rst$" . rst-mode)
("\\.rest$" . rst-mode)) auto-mode-alist))



彩色语法内容

可以用不同彩色显示程序的不同部分。

;; for global font lock mode
(global-font-lock-mode t)


临时标记模式

可以使标记的区域不总是高亮显示。

;; transient mark mode
(setq transient-mark-mode t)


显示匹配括号

输入右括号时显示匹配的左括号。

;; show paren mode
(show-paren-mode t)


提供最近访问文件信息


;; For recent files feature
(require 'session)
(setq session-save-file "c:\\.emacsd\\.session")
(add-hook 'after-init-hook 'session-initialize)


用百分号匹配括号

(global-set-key "%" 'match-paren)
(defun match-paren (arg)
"Go to the matching parenthesis if on parenthesis otherwise insert %."
(interactive "p")
(cond ((looking-at "\\s\(") (forward-list 1) (backward-char 1))
((looking-at "\\s\)") (forward-char 1) (backward-list 1))
(t (self-insert-command (or arg 1)))))


打印

NT Emacs打印总是不成功。现在只好用一个麻烦的办法: 用命令M-x ps-spool-buffer-with-face可以生成 一个包含了当前缓冲区内容的PS文件,找到这个PS文件对应的缓冲区并把它存为一个PS文件然后再打印这个PS文件。在网上查到了设置用gs直接连接打印的办法但是显示打印完毕却没有任何实际动作。


Using Abbreviations(使用简写)

Emacs can automatically correct your spelling mistake as you type (such as correcting "thier" with "their"), or expand your own abbreviations for full word (such as replacing "Indie" with "Independent"). Emacs can do this when you enable the "Abbrev" minor mode.

Add the following code to your ~/.emacs file to enable the Abbrev minor mode, to load in abbreviations from ~/.abbrev_defs and to save changes you make to the abbreviations table when you exit Emacs.

;; ===== Automatically load abbreviations table =====

;; Note that emacs chooses, by default, the filename
;; "~/.abbrev_defs", so don't try to be too clever
;; by changing its name


(setq-default abbrev-mode t)
(read-abbrev-file "~/.abbrev_defs")
(setq save-abbrevs t)

To display a list of the current abbreviations Emacs uses, enter the command list-abbrevs.


Highlight Current Line(高亮当前行)

To make Emacs highlight the line the curosr is currently on, add the following to your ~/.emacs :

;; ===== Set the highlight current line minor mode =====

;; In every buffer, the line which contains the cursor will be fully
;; highlighted


(global-hl-line-mode 1)


Set Indent Size(设置缩进量)

To set the standard indent size to some value other than default add the following to your ~/.emacs :

;; ===== Set standard indent to 2 rather that 4 ====

(setq standard-indent 2)


Line-by-Line Scrolling(按行滚动)

By default Emacs will scroll the buffer by several lines whenever the cursor goes above or below the current view. The cursor is also returned to the middle-line of the current view.

This can be confusing to work with since the cursor appears to jump around. If you prefer to have the cursor remain at the top or bottom of the screen as scrolling takes place then use:

;; ========== Line by line scrolling ==========

;; This makes the buffer scroll by only a single line when the up or
;; down cursor keys push the cursor (tool-bar-mode) outside the
;; buffer. The standard emacs behaviour is to reposition the cursor in
;; the center of the screen, but this can make the scrolling confusing


(setq scroll-step 1)


Turn Off Tab Character(取消制表符)

To stop Emacs from entering the tab character into your files (when you press the "tab" key) add the following to your ~/.emacs :

;; ===== Turn off tab character =====

;;
;; Emacs normally uses both tabs and spaces to indent lines. If you
;; prefer, all indentation can be made from spaces only. To request this,
;; set `indent-tabs-mode' to `nil'. This is a per-buffer variable;
;; altering the variable affects only the current buffer, but it can be
;; disabled for all buffers.

;;
;; Use (setq ...) to set value locally to a buffer
;; Use (setq-default ...) to set value globally
;;

(setq-default indent-tabs-mode nil)


Enable Wheel-Mouse Scrolling(打开鼠标滚轮)

By default Emacs does not respond to actions of a scroll button on a wheel mouse; however, it can be made to do so with a simple configuration entry:

;; ========== Support Wheel Mouse Scrolling ==========


(mouse-wheel-mode t)


Prevent Backup File Creation(禁止产生备份)

By default Emacs will automatically create backups of your open files (these are the files with the ~ character appended to the filename). Add the following to your ~/.emacs to prevent these backup files from being created :

;; ========== Prevent Emacs from making backup files ==========

(setq make-backup-files nil)


Saving Backup Files to a Specific Directory(指定备份目录)

Backup files can occassionally be usful, so rather than completely disabelling them, Emacs can be configured to place them in a specified directory. Do this by adding the following to your ~/.emacs files:

;; ========== Place Backup Files in Specific Directory ==========

;; Enable backup files.

(setq make-backup-files t)

;; Enable versioning with default values (keep five last versions, I think!)

(setq version-control t)

;; Save all backup file in this directory.

(setq backup-directory-alist (quote ((".*" . "~/.emacs_backups/"))))


Enable Line and Column Numbering(显示行号列号)

Emacs can display the current line and column number on which the cursor currently resides. The numbers appear in the mode-line :

;; ========== Enable Line and Column Numbering ==========

;; Show line-number in the mode line

(line-number-mode 1)

;; Show column-number in the mode line

(column-number-mode 1)


Set Fill Column(设置列宽)

The fill column influences how Emacs justifies paragraphs. For best results choose a value less than 80:

;; ========== Set the fill column ==========

(setq-default fill-column 72)


Enable Auto Fill mode(设置自动填充)

Auto fill is useful when editing text files. Lines are automatically wrapped when the cursor goes beyond the column limit :

;; ===== Turn on Auto Fill mode automatically in all modes =====

;; Auto-fill-mode the the automatic wrapping of lines and insertion of
;; newlines when the cursor goes over the column limit.

;; This should actually turn on auto-fill-mode by default in all major
;; modes. The other way to do this is to turn on the fill for specific modes
;; via hooks.

(setq auto-fill-mode 1)


Treat New Buffers as Text(新缓冲区作为文本)

Specify that new buffers should be treated as text files:

;; ===== Make Text mode the default mode for new buffers =====

(setq default-major-mode 'text-mode)


Set Basic Colours(设置基本颜色)

Emacs does allow the various colours it uses for highlighting code to be configured by the user. However a quick way to set the basic colours used f or all buffers is:

;; ========= Set colours ==========

;; Set cursor and mouse-pointer colours

(set-cursor-color "red")
(set-mouse-color "goldenrod")

;; Set region background colour

(set-face-background 'region "blue")

;; Set emacs background colour

(set-background-color "black")


Delete the Current Line(删除当前行)

In order to provide Emacs with a key for deleting the current line an appropriate delete-line function has to be first defined, and then a key-sequence binding defined to invoke it :

;; ===== Function to delete a line =====

;; First define a variable which will store the previous column position

(defvar previous-column nil "Save the column position")

;; Define the nuke-line function. The line is killed, then the newline
;; character is deleted. The column which the cursor was positioned at is then
;; restored. Because the kill-line function is used, the contents deleted can
;; be later restored by usibackward-delete-char-untabifyng the yank commands.

(defun nuke-line()
"Kill an entire line, including the trailing newline character"
(interactive)

;; Store the current column position, so it can later be restored for a more
;; natural feel to the deletion

(setq previous-column (current-column))

;; Now move to the end of the current line

(end-of-line)

;; Test the length of the line. If it is 0, there is no need for a
;; kill-line. All that happens in this case is that the new-line character
;; is deleted.

(if (= (current-column) 0)
(delete-char 1)

;; This is the 'else' clause. The current line being deleted is not zero
;; in length. First remove the line by moving to its start and then
;; killing, followed by deletion of the newline character, and then
;; finally restoration of the column position.

(progn
(beginning-of-line)
(kill-line)
(delete-char 1)
(move-to-column previous-column))))

;; Now bind the delete line function to the F8 key

(global-set-key [f8] 'nuke-line)


LaTeX使用经验

LaTeX使用经验

enumerate环境中自定义序号

可以用\itme[自定序号]的方法。

Emacs中编辑LaTeX

除启用AUCTeX外,还用Meta-X reftex-mode启用retex模式。可以帮助管理公式标签。用C-c =显示所有章节目录,用C-c )选择一个标签引用,选e时显示可用的公式标签。显示可选的标签时,用r键更新可选标签列表。

关于Plain TeX制表

方法1. 均分

\settabs 4\columns % 平均分成四栏。

\+ 栏1 & 栏2 & 栏3 & 栏4 \cr

\+ & & 栏3 \cr

没有结束命令,一直有效,栏内左对齐,可越界。为了右对齐可用如"\hfill 栏3", 为居中对齐可用如"\hfill 栏3 \hfill"。



方法2. 用例子给定宽度。如:

\settabs \+\indent 栏1 \quad & 栏2 \quad & \cr

\+ 栏1 & 栏2 & 栏3 \cr

例子行不输出。


表格居中及上下留空方法如:

$$\vbox{表格内容

}$$



方法3. 基于模版。用\halign{...}命令。如

\halign{\indent#\hfil&\quad#\hfil\cr

栏1 & 栏2 & 栏3 \cr

......

}

其中#在模版中代表某格内容。为了表格单元居中可在两边都加上\hfil。在\halign内改变字体只对一个单元格起作用。



表格两行间加空的办法:

\noalign{纵向空白}

其中“纵向空白”如\smallskip, \medskip, 甚至于可以用文字。


表格规定栏间空白大小的方法:

\tabskip=1em plus2em minus .5em

\halignto \hsize{\hfil\bf# & \hfil\it#\hfil&

\hfil#\hfil & \hfil#\hfil & #\hfil\cr

......

}

上例规定了表格宽为行宽,有五栏,第一栏右对齐且粗体,第二栏居中且斜体,第三栏和第四栏居中,第五栏左对齐。\tabskip用来规定两栏之间的间隔,在\halign的例子行内定义\tabskip可以修改某一个栏间空,这样可以不同的栏间有不同的间空。如

\halign{\tabskip=4pt #\hfil & \tabskip=10pt \hfil#\hfil & #\hfil \cr

栏1(左对齐) & 栏2(居中) & 栏3(左对齐) \cr
......}
如果在模版中用了复杂的格式或文本而某个单元格不需要,可以在该单元格中用如"\omit 自定义内容"来取消模版中的规定。

表格按小数点对齐的方法:可以把"~"临时定义为\phantom{0}然后补齐数字。

多栏合并的方法:
合并栏 \hidewidth && \cr
可右对齐,&号不能省,\hidewidth可左对齐。另一方法是用\multispan{3}即合并三栏。

表格中的填充命令: \hfill为填空白;\hrulefill为填横线;\hdotfill为填虚线。

表格线:为了竖线能连接在一起,要用
\offinterlineskip
即不允许多余(可变)的行间距。用\vrule#在模版中加入一条竖线,正文中需要用空栏留出竖线为止。如果某行需要不划竖线可以用\omit,或\height10pt用来自定义竖线高度。例如:
\vbox{\offinterlineskip
\hrule % 上表格横线
\halign{ & \vrule# & % 这里是一条竖线
\strut\quad\hfil#\quad\cr % \strut是可以重复利用的。
height2pt & \omit && \omit & \cr % 多余的空
& Year\hfil && World Population & \cr % 在第一个&前有竖线,在两个&&间有竖线,&和\cr间有竖线
\height2pt & \omit&&\omit&\cr % 多余的行间空
\noalign{\hrule} % 横线
& 8000\BC && 5,000,000 & \cr
\height2pt & \omit && \omit & \cr }
\hrule} % 底横线
横线也可用\multispan{5}\hrulefill.
另一例子:
\vbox{\tabskip=0pt \offinterlineskip
\def\tabrule{\noalign{\hrule}}
\halign to 200pt{\strut#&\vrule# % 左竖线
\tabskip=1em plus 2em &
\hfil#&\vrule#&\hfil#\hfil&\vrule#& % 右对齐单元格,竖线,居中栏,竖线
\hfil#&\tabskip=0pt\cr\tablerule % 右对齐单元格,表格线与单元格间无空,横线
&& \multispan{5}\hfil AT\&T Common Stock \hfil & \cr\tablerule
&& \omit\hidewidth Year \hidewidth &&
\omit\hidewidth Price \hidewidth &&
\omit\hidewidth Dividend \hidewidth & \cr\tablerule
&& 1971 && 41--54 && $ 2.60 & \cr\tablerule
& \multispan{7} *(first quarters only)\hfil\cr}} % 合并的栏
\strut是一个隐形的竖线,起到行间胶水(glue)的作用。\hidewidth使标题宽度不影响栏宽。


现代刊物中常见的文献引用方式

我们用BibTeX管理LaTeX的文献,假设我们有一个数据库mybiblib,为产生引用,只要在文章末尾加上
\bibliography{mybiblib}
\bibliographystyle{plainnat}

并在前言部分加上

\usepackage{natbib}

然后运行LaTeX编译,再运行bibtex,再运行两次LaTeX编译就可以得到文章末尾的文献列表和文章中的引用,引用如\cite{Durbin02}可以变成Durbin & Koopman(2002), 相应的文献格式化为

J. Durbin and S. J. Koopman. A simple and effcient simulation smoother for
state space time series analysis. Biometrika, 89(3):603-615, 2000.

如果把bibliograpystyle改成agsm,则文献格式化结果为

Durbin, J. & Koopman, S. J. (2002), ‘A simple and effcient simulation smoother
for state space time series analysis’, Biometrika 89(3), 603-615.


BibTeX文献库管理软件JabRef

数学方向的研究人员写作一般使用LaTeX,当文献较多时文献引用由BibTe来管理比较有效。但是,直接用文本格式来编辑BibTeX的数据库 (*.bib文件)比较麻烦,Emacs中的对BibTeX编辑的支持也比较一般。所以,最好有一种窗口菜单形式的软件来管理文献数据库。
经过搜索我发现JabRef比较适用于管理BibTeX数据库。该程序是自由软件,基于Java所以除了可以在MS Windows上可以运行以外,在LinuxMac OS上也可以运行,直接以.bib格式的文件为数据库,可以用图形窗口方式编辑文献条目。另一个可能有用的免费文献数据库管理软件是Biblio Express,可以用于Word写作的文献库管理,兼容其它的商业文献数据库管理软件。


图形目录和图形缺省扩展名

\graphicspath{{demofigs/}} % 指定图形文件的读取目录
\DeclareGraphicsExtensions{.pdf,.jpg,.png} % 指定没有扩展名时图形文件缺省扩展名

Beamer包使用经验

在Beamer制作的文章中如果需要用verbatim环境, \verb, lstlisting等原样显示的功能,可以对frame环境加[containsverbatim]选项。但这样不能使用遮盖显示,另一办法是在 frame前面用\defverb\codea|someone@abc.com|定义命令然后在frame中调用命令\codea。对verbatim 环境,定义命令的格式如:
\defverbatim\codeb{%
\begin{verbatim}
...
\end{verbatim}
}

右侧有目录,且目录中小节只显示当前节的小节,浅蓝白色:
\usetheme[hideothersubsections]{Goettingen} % 菜单在右,浅蓝白色, 小节只显示当前节


Beamer主题(theme)分类

%% 一、不带导航条的主题有:default,boxes,Bergen,Boadilla,
%% Madrid,Pittsburgh,Rochester.这些主题要注意大小写。
%% 二、树形导航条的主题:Antibes,JuanLesPins,Montpellier。
%% 三、带目录的侧边导航条的主题:Berkeley,PaloAlto,Gottingen,
%% Marburg,Hannover。
%% 四、微型导航条的主题:Berlin,Ilmenau,Dresden,Darmstadt,
%% Frankfurt,Singapore,Szeged
%% 五、带节、小节目录的主题:Copenhagen,Luebeck,Malmoe,Warsaw。

%\usetheme{Antibes} % 菜单在上, 深蓝白色
%\usetheme{Copenhagen} % 菜单在上, 深蓝白色, 同Warsaw
%\usetheme{Luebeck} % 菜单在上, 深蓝白色, 同Warsaw
%\usetheme{Malmoe} % 菜单在上, 深蓝白色, 同Warsaw
%\usetheme{Warsaw} % 菜单在上, 深蓝白色

%\usetheme{JuanLesPins}% 菜单在上仅显示当前路径, 深蓝白色
%\usetheme{Montpellier}% 菜单在上仅显示当前路径, 浅蓝白色

%\usetheme{Berlin} % 菜单在上且可显示每小节的页面数, 深蓝白色
%\usetheme{Dresden} % 菜单在上且可显示每小节的页面数, 深蓝白色, 同Berlin
%\usetheme{Ilmenau} % 菜单在上且可显示每小节的页面数, 深蓝白色, 同Berlin
%\usetheme{Darmstadt} % 菜单在上且可显示每小节的页面数, 深蓝白色
%\usetheme{Frankfurt} % 菜单在上且可显示每小节的页面数, 深蓝白色
%\usetheme{Singapore} % 菜单在上且可显示每小节的页面数, 浅蓝白色, 不显示小节名

%\usetheme{Bergen} % 菜单在左, 深蓝白色
%\usetheme{Berkeley} % 菜单在左, 深蓝白色
%\usetheme{Hannover} % 菜单在左, 标题靠右, 浅蓝白色
%\usetheme{PaloAlto} % 菜单在左, 深蓝白色

%\usetheme{Goettingen} % 菜单在右,浅蓝白色
%\usetheme{Marburg} % 菜单在右, 深蓝白色

%\usetheme{Boadilla} % 无菜单, 浅蓝白色
%\usetheme{Madrid} % 无菜单, 深蓝白色
%\usetheme{Pittsburgh} % 无菜单, 深蓝白色
%\usetheme{Rochester} % 无菜单, 深蓝白色


%\usetheme{Warsaw} % 菜单在上, 深蓝白色
%\usetheme{Boadilla} % 无菜单, 浅蓝白色
%\usetheme{JuanLesPins}% 菜单在上仅显示当前路径, 深蓝白色
%\usetheme{Singapore} % 菜单在上且可显示每小节的页面数, 浅蓝白色, 不显示小节名

R经验汇编

R使用经验

本文将以逐渐增加的方式总结一些R的小问题的处理方法。 这里的一部分小窍门来自Grant V. Farnsworth: Econometrics in R

重要链接

R-Forge: http://r-forge.r-project.org/ 各种R附加软件包的存放地点。

Access表读写

假设有Access数据库在文件c:/Friends/birthdays.mdb中,内有两个表MenWomen,每个表包含域Year, Month, Day, First Name, Last Name, Death。域名应尽量避免用空格。

例1:读入女性所有信息:

> require(RODBC)

> con <- odbcConnectAccess("c:/Temp/birthdays.mdb")

> women <- sqlQuery(con, 'select * from Women')

> print(women)

> close(con)

例2:显示数据库目录

> require(RODBC)

> con <- odbcConnectAccess("c:/Temp/birthdays.mdb")

> # Table names. Ignore those starting with 'MSys'

> sqlTables(con)$"TABLE_NAME"

> # Column names in a table

> sqlColumns(con, "Women")$"COLUMN_NAME"

> close(con)

例3:较复杂的查询

> require(RODBC)

> con <- odbcConnectAccess("c:/Temp/birthdays.mdb")

> # Read Year, Last Name and First Name.

> # Rename Last Name to LastName, First Name to FirstName

> # Read first 5 rows where First Name is not 'Carl'

> men <- sqlQuery(con, "select top 5 Year, [First Name] as FirstName, [Last Name] as LastName from Men where [First Name]<>'Carl'")

> close(con)


Excel表格读写



基本办法是转换为其他格式如CSV格式再读。在Windows下有xlsReadWrite包,可以读写.XLS文件。RODBC包也可以支持Excel文件的读写。
小量数据可以选中一个矩形区域复制,然后在R中用

> myDF <- read.delim("clipboard")

也可以从R中复制数据集:

> ## export 'iris' data to clipboard

> write.table(iris, "clipboard", sep = "\t", col.names = NA)

> ## then open up MS Excel and paste (ctrl-v) in iris data

用ODBC读取Excel文件:

> library(RODBC)

> MyExcelData <- sqlFetch(odbcConnectExcel("Test.xls"), sqtable = "Sheet1", na.strings = "NA", as.is = T)

> odbcCloseAll()

用xlsReadWrite的例子:

> library( xlsReadWrite )

> ### create some test bike data

> tdat <- data.frame( Price = c( 6399, 3699, 2499 ), Amount = c( 2, 3, 1 ),

Date = c( 39202, 39198, 39199 ), row.names = c( "Pro machine", "Road racer", "Streetfire" ) )

> ### write

> write.xls( tdat, "bikes.xls" )

> ### read and check: read as data.frame

> bikes1 <- read.xls( file = "bikes.xls" )

> if (!identical( tdat, bikes1 )) stop( "oops, not good..." )

> # read as data.frame (custom colnames, date as iso-string)

> bikes2 <- read.xls( file = "bikes.xls", colNames = c( "", "CHF", "Number", "Date" ),

from = 2, colClasses = c( "numeric", "numeric", "isodate" ) )

> if (!all( tdat$Date == isoStrToDateTime( bikes2$Date ) )) stop( "oops, not good..." )

> # read as matrix

> bikes3 <- read.xls( file = "bikes.xls", type = "double" )

> if (!identical( as.matrix( tdat ), bikes3 )) stop( "oops, not good..." )



简单交互式图形界面

R 通过对Tcl/Tk的支持(tcltk包)实现了图形界面(GUI)功能,但是需要的编程略微复杂。rpanel是建立在tcltk包基础上的一个包,它 用很简单的几个语句就可以建立一个调控运行参数的界面,主要用来实时更新图形,修改界面上的控制参数则图形立刻刷新。真的很容易。



表格数据

table()计算频数。

tapply(x, fac, func)facx分组在每组内计算函数funcfac还可以是由若干因子向量组成的列表,这时将交叉分类后计算func函数。

几个因子完全组合的结构数据集可以用expand.grid(li)实现,li是一个列表,每个列表变量包含一个因子的水平。如果ll是某个包含若干因子变量的列表,则expand.grid(lapply(ll, levels))可以构造所有可能水平组合的数据框。


要把矩阵按其显示格式写入一个文本文件,办法如

write(t(A), file="filename", ncolumns=ncol(A)).


C++/C中使用NA

有时需要把NA传到C++/C中。为此,C中要包含R.h头文件,并用ISNA(x[0])这样的方法判断x[0]是否为NA,编译时最好用标准的

R CMD SHLIB yourcprog.cpp

方法编译。在R中调用时.C中要加上NAOK=TRUE选项。


Linux中非超级用户安装包

假设你在自己的主目录下建立了.R/library子目录,并建立了一个~/.Renviron文件,其中包含如下行:

R_LIBS=”~/.R/library”

则可以把R的附加包安装在自己的目录中:
R CMD INSTALL -l ~/.R/library mypackage.tar.gz
进入R后可以直接访问在~/.Renviron中定义在R_LIBS目录中安装的包。


运行记录

数据分析运行中间可能输出大量的信息,在调试程序时可能需要查看这些信息。在Emacs中用ESS支持直接在Emacs窗口中运行R当然可以保存这些输出,但是在Emacs中运行如果出错(尤其是调用自己编写的C程序的错误)不容易恢复。用sink()函数可以保存输出到文件,但这时在屏幕上就看不到输出。其实,sink()函数加一个split=TRUE选项就可以实现既输出到文件同时又显示在屏幕的效果。如果图形也能作到这点就好了。


R命令行中设置当前工作目录

getwd()查询当前工作目录,用setwd('subdir')设置当前工作目录。 调用list.files()可以查看当前目录中内容, 用list.files(pattern='.*[.]r$')可以列出所有以“.r”结尾的文件。


集合函数

union(x, y)
intersect(x, y)
setdiff(x, y)
setequal(x, y)
is.element(el, set)

fft的数学公式

Rfft函数可以进行离散傅立叶变换。 设x为长度n的向量,y=fft(x),则
y[k] = sum(x * complex(argument = -2*pi * (0:(n-1)) * (k-1)/n))

w_k = \frac{k-1}{n}, k=1,2,...,n
y_k = \sum_{j=1}^n x_j \exp(-i 2\pi w_k (j-1)).
注意没有除以n。另外,若y=fft(x), z=fft(y, inverse=T), x == z/length(x)


R的日期类

DateR的日期类,实际保存为实数值。转换如d=as.Date("1996-03-17", format="%Y-%m-%d"), 而显示可用如format(d, format="%Y-%m-%d")。格式中%Y是四位的年份,%m是数字的月份,%d是日期,%y是两位的年份,%b是英文所写的月份,%B是英文全称的月份。参见strptime的帮助。


顺便提一句,在SAS中如果要把如s=”1997-03-15”这样的字符串值转换成SAS日期,方法是date=input(s, yymmdd10.)


数据框横向合并

merge 函数。


巨大文件的读取


先用file打开,然后用readLines分批读入, 或用scanwhat参数和nlines参数分批读入。


读入复制到系统剪贴板中的数据


read.table("clipboard")


回归系数估计的方差阵

rs <- summary(lm.res)
CovMat <- rs$sigma^2 * rs$cov


加权回归


只要在lm调用时加weight选项。


Logitprobit回归

glm


多项logit回归


nnet包中的multinom函数。


有序Logit/Probit


MASS包中的polr函数。


带删失变量的回归


survreg并指定dist="gaussian"即可。


分位数回归

quantreg包中的rq函数。


稳健回归

MASS包中的rlm函数。


非线性最小二乘

nls函数。


时间序列函数

lag可以计算滞后序列,但只能作用于时间序列对象,对一般向量会得出错误结果。 diff计算差分。ts.union可以形成多元时间序列。 filter函数可以计算递推的或卷积的滤波。 arima可以拟合ARIMA模型。 fracdiff库的fracdiff可以拟合分数ARIMA模型。 tseries包中的garch可以拟合GARCHARCH模型。 fSeries包中的garchFit可以拟合较复杂的包含GARCH的模型。 acfpacf函数可以作自相关和偏自相关图。


时间序列检验

car包中的durbin.watson函数可以对lm对象进行Durbin-Watson自相关检验。 ts包中的Box.test可以进行Box-PierceLjung-Box白噪声检验。 tseries包中的adf.test可以进行Dickey-Fuller单位根检验。


curve函数

用于函数或表达式作图,与add=T选项配合可以在已有的图上添加曲线。


等值线图

contour函数。可以用contourLines添加。 lattice包中有类似的levelplotcontourplot函数。


添加标注

text, lines, points, arrowslegend等。用locator定位。


输出到图形文件

直接用图形设备postscript, pdf, png, jpg, xfig等。


图中用数学符号

用如main=substitute(y==Psi*z-sum(beta[0]^gamma)),会变成数学符号。 下标用方括号表示。等号用两个等号表示。 还可以给substitute一个额外的list参数表示要代入实际值的变量。 混合文本如
main=substitute(paste("t-stat of ", beta[0]))


Kronecker

A %x% B表示。


优化

optim, nlm, optimize。 类似作用的有uniroot(一元方程求根)diriv(数值微分)constrOptim(约束优化)


数值积分

一元用integrate,多元用adapt包中的adapt函数。


代替循环的函数

对矩阵用apply,对列表用lapply,对向量用sapply


计时

system.time(表达式)计算一个表达式的运行时间; 用proc.time得到当前时间,两次调用的差表示时间间隔。


在为R准备的C程序中使用R的随机数发生器

要调入头,在生成随机数前调用GetRNGstate(),生成完毕调用SetRNGstate()。实际产生一个正态分布随机数如rnorm(0.0, 1.0)。编译用
R CMD SHLIB mycode.c


错误处理

options函数调用中设error=recover可以使得出错时进入调试状态。 设warn=1可以使警告信息输入不滞后。 设warn=0取消警告信息,而warn=2使警告信息变成错误。


输出为LaTeX

Hmisc包中的latex函数,如latex(summary(lm(y~x)))。 或用xtable包中的xtable函数。用Hmisclatex函数时,加NA=””可以把缺失值显示成空白,输出数据集时,行名将作为第一栏。


用RPanel建立图形界面

用rp.control()函数建立一个窗口,用title指定标题。返回值保存一个代表此窗口的列表变量,列表中为图形数据。rp.control多余的参数被保存在列表中。如:

density.panel <- rp.control(title="Density estimation",

y=A1203, sp=r/8)

其中y,sp,model是额外的变量,被存放在结果列表density.panel中。


在窗口中添加控件时以窗口变量为第一自变量,如:

rp.slider(panel=density.panel, var=sp, from=r/50, to=r/4,

action=density.draw, title="Bandwidth")

在density.panel窗口中增加一个滑块控件,其中var参数指定窗口列表中已有的变量sp,变量的值将由此控件修改。action是修改值时更新用的响应函数。响应函数density.draw以一个窗口变量为输入,并返回可能修改后的窗口变量。


rp.radiogroup添加单选钮,如:

rp.radiogroup(panel=density.panel, var=sp.method,

values=c("normal", "plug-in", "manual"),

title="Bandwidth Selection", action=density.draw)

其中var=sp.method在density.panel列表中定义一个sp.method变量并由此单选钮组选择其取值。


rp.checkbox添加复选框,如:

rp.checkbox(panel=density.panel, var=model,

title="Normal band", action=density.draw)

指定density.panel列表变量model并由此控件控制开关。


rp.doublebutton添加加减按钮,如:

rp.doublebutton(panel=density.panel, var=sp, step=1.02,

log=TRUE, range=c(diff(range(A1203))/50, NA),

title="Bandwidth")

结果是并排的减号和加号,可以控制一个窗口列表变量的增减。var=sp指定要控制的窗口列表变量,step是变化量,log=TRUE指定是用等比方式变化,range给出变换的界限。


R中tcltk包的使用

例子见 http://bioinf.wehi.edu.au/~wettenhall/RTclTkExamples/ 。Tcl/Tk的原始参考资料见 http://www.tkdocs.com/widgets/index.htmlhttp://www.tcl.tk/man/tcl8.5/contents.htm


要先有一个主窗口,用tktoplevel生成,如:

root <- tktoplevel()

要指定窗口标题,用如:

tktitle(root) <- "tcltk测试"


生成按钮用command指定操作,如:

exit.but <- tkbutton(root,text="退出", command=function() tkdestroy(root))

tkgrid(exit.but) ## 用来摆放按钮

tkfocus(root)

按钮的对应操作是关闭窗口。


提示信息对话框:

res <- tkmessageBox(title="计算程序", message="试验时间数据输入错误!", icon="error",type="ok")

可以用icon="info", icon="warning"。如果type="yesnocancel"结果会有三个按钮, 用default="yes"指定缺省按钮。用as.character(res)查看结果。


用tclVar建立tcl变量,用tclvalue访问其值,如:
done <- tclVar(0) ## 建立tcl变量done, 值为0.
OK.but <- tkbutton(root, text=" OK ", command=function() tclvalue(done)<-1)
按钮的作用是把tcl变量done的值赋值为1. 可以用tclvalue(done)访问这个值,如果是整数应该用as.integer(tclvalue(done))转换。

用tkbind给某个窗口事件规定响应,如:
tkbind(root, "", function() tclvalue(done) <- 2)

用tkwait.variable等待tcl变量的值改变,如:
tkwait.variable(done)

用tklabel添加一个标签控件,如:
tkgrid(tklabel(root,text="This is a text label"))
如果需要修改标签内容,可以用tcl变量,如:
labelText <- tclVar("This is a text label")
label1 <- tklabel(root,text=tclvalue(labelText))
tkconfigure(label1,textvariable=labelText) ## 把控件与tcl变量关联。
tkgrid(label1)
ChangeText <- function() tclvalue(labelText) <- "This text label has changed!"
ChangeText.but <- tkbutton(tt,text="Change text label",command=ChangeText)
tkgrid(ChangeText.but)
其中用了tkconfigure把标签控件label1与变量labelText建立了联系。

用tkentry指定文本输入条,如:
tcl.en <- tclVar(1.5)
en <- tkentry(root, textvariable=tcl.en, width=20)
这样可以用as.double(tclvalue(tcl.en))访问输入的值。

用tktext指定文本输入框,如:
txt <- tktext(root, width=20, height=10)
其中宽和高的单位是字符。访问内容如:
s <- as.character(tclvalue(tkget(txt, "0.0", "end"))) ## 全部内容
s <- gsub(",", " ", s) ## 把逗号替换成空格
sc <- textConnection(s) ## 生成输入流
x <- scan(sc)
close(sc)

用tkframe作为容器容纳控件。如:
fr <- tkframe(root, padx=5, pady=5)
其 中padx和pady是在其必须的大小上加富余的空白。用relief和borderwidth指定边界形式,relief有raised, sunken, flat, ridge, solid, groove, 必须指定borderwidth如borderwidth=3才能显示效果。

用tkwidget生成一个一般Tk控件,用type指定类型,如:
fr <- tkwidget(root, type="labelframe", text="选择")

摆放控件用tkpack或tkgrid。tkpack沿上、下、左、右之一边缘摆放,tkgrid可以对准摆放,比如,la1和en1是输入的标签和输入条,la2和en2是另一对,则用
tkgrid(tklabel(root, text="输入部分"), columnspan=2)
tkgrid(la1, en1)
tkgrid(la2, en2)
其中第一个“输入部分”标签占了两列。在tkpack中用padx和pady指定左右和上下的间隙,如:
tkpack(ok.but, side="bottom", padx=10, pady=20)

在MS Windows环境下,为了能单独运行图形界面而不显示R原来的图形界面,可以在程序最后写上:
tcl.exit <- tclVar(0)
tkbind(root, "", function() tclvalue(tcl.exit) <- 1)
tkwait.variable(tcl.exit)
这样在批运行时不至于马上结束。批运行的命令是
\pathToRInstall\bin\rcmd BATCH testtk.r

\pathToRInstall\bin\rterm --vanilla <>&1