Skip to content

如何创建自己的R包

Ricky Woo edited this page Sep 30, 2017 · 9 revisions

R在我们的统计学分析和统计学工具的开发中的作用是不言而喻的,有时候我们需要将我们的一些工作、代码组织成一个R包,以便重复使用,那么,如何去创建自己的R包呢?这里,我们给出R包创建的几个关键步骤:

1. 准备好你的R函数以及示例的数据集(Prepare your R functions and the example data set)

# myfunctions.R
linmodEst <- function(x, y) {
	## compute QR-decomposition of x
	qx <- qr(x)
	## compute (x'x)^(-1) x'y
	coef <- solve.qr(qx, y)
	## degrees of freedom and standard deviation of residuals
	df <- nrow(x)-ncol(x)
	sigma2 <- sum((y - x%*%coef)^2)/df
	## compute sigma^2 * (x'x)^-1
	vcov <- sigma2 * chol2inv(qx$qr)
	colnames(vcov) <- rownames(vcov) <- colnames(x)
	ans<-list(coefficients = coef,
	vcov = vcov,
	sigma = sqrt(sigma2),
	df = df)
	return(ans)
}

## mydata.txt
x	y
0.25292125181295	1.83182384062728
0.480541671393439	-1.21621304198827
0.89594656531699	0.205224147138891
0.815897075459361	0.928879979716545
0.214073656126857	-0.509798487809603
0.310535365482792	0.917733168734492
0.398109727306291	-1.13258614629315
...

2. 用函数base::package.skeleton()创建R包的基本结构(Build R package structure)

一个标准的R包包含以下一些文件和目录:

  • DESCRIPTION
  • NAMESPACE
  • Read-and-delete-me
  • man目录包含包的帮助文档
  • R目录包含R代码
  • data目录存放数据集
  • inst目录存放一些杂项和类似vignette的东西
  • src目录存放一些用C或者其他语言编写的源代码

$\S$创建R包mypkg

tmpdir <- "tmp"
if (file.exists(tmpdir)) unlink(tmpdir, recursive=TRUE)
dir.create(tmpdir)
source("./pkgFiles/myfunctions.R")
mydata <- read.table("./pkgFiles/mydata.txt", header=TRUE)
namespace <- c("linmodEst", "mydata")
package.skeleton(name="mypkg", namespace.path=tmpdir, force=TRUE)

3. 编写DESCRIPTION文件

Package: mypkg
Type: Package
Title: What the package does (short line)
Version: 0.1
Date: 2017-10-21
Author: Donald Duck
Maintainer: Donald Duck <[email protected]>
Description: This is an example R package
Depends: geepack, methods, yeastCC, org.Sc.sgd.db, LiquidAssociation
License:  GPL (>= 2)

4. 编写NAMESPACE文件

exportPattern("^[[:alpha:]]+")
export("linmodEst")

5. 在man目录中编写帮助文件*.Rd

\name{linmodEst} # 函数名
\alias{linmodEst} # 函数别名
%- Also NEED an '\alias' for EACH other topic documented here.
\title{          # 帮助文档的题目
Perform QR-decomposition regression
}
\description{ # 函数功能的描述
An alternative way to perform linear regression y=bo + b1 *x
}
\usage{       # 用法
linmodEst(x, y)
}
%- maybe also 'usage' for other objects documented here.
\arguments{  # 参数列表
  \item{x}{
 is the design matrix
}
  \item{y}{
 is a numerical vector that represents the outcome (response) variable
}
}
\details{ # 函数详细用法的说明
For numerical reasons it is not advisable to compute beta estimate using the above formula, it is better
to use, e.g., a QR decomposition or any other numerically good way to solve a linear system of
equations
}
\value{ #函数返回值
 \item{coefficients}{The estimates of beta coefficients}
 \item{vcov}{The covariane matrix of the beta coefficients}
 \item{sigma}{The estimated residual variance}
 \item{df}{The degree of freedom}
}
\references{ # 参考文献
1. Donald Duck's paper here
}
\author{  # 作者
Donald Duck
}
\note{ # 说明
This is an example
}


\seealso{ # 相似函数
lm
}
\examples{ # 示例
data(mydata)
design<-cbind(1, mydata$x)
linmodEst(design, mydata$y)

% Add one or more standard keywords, see file 'KEYWORDS' in the
% R documentation directory.
\keyword{QR-decomposition} # 关键词条

6. 编写介绍R包的小短文(vignette)

一般来说,vignette可以用Sweave或者knitr编写*.Rnw文件,可以在\LaTex中嵌套R代码,运行后可生成pdf文件:

\documentclass{article}
\usepackage{Sweave}
\begin{document}
Some content
<<>>=
my R code chunk
data<-read.delim(”mydata.txt”)
n<-nrow(data)
@
There are \Sexpr{n} observations.
\end{document}

其中<<>>=@之间可以嵌入R脚本,然后执行Sweave()或者knit2pdf()等函数可以转化为pdf文件。

<<>>中包含的宏指令选项

  • <<eval=TRUE/FALSE>>:是否运行R脚本
  • <<echo=TRUE/FALSE>>:是否在latex和pdf中显示R脚本
  • <<fig=TRUE/FALSE>>:是否显示图形
  • <<figname, fig=TRUE, includes=FALSE>>

Sweave()Rnw转换为pdf

library(tools)
Sys.setenv(PATH = paste(Sys.getenv("PATH"),"/usr/texbin", sep = ":"))
cpwd<-getwd()
setwd("./misc")
Sweave("test.Rnw")
texi2dvi("test.tex", pdf=TRUE)
setwd(cpwd)

然后建立目录misc/doc,将Rnw文件和pdf文件拷贝到这个目录就可以了。

7. 用R CMD BUILD建立和安装R包

8. 用R CMD check检查R包

在最后,不要忘了运行:

sessionInfo()

A bioinformatics wiki for the course BI462.

Clone this wiki locally