@fanxy 2018-04-02T10:45:05.000000Z 字数 3548 阅读 2396

# R 语言常用命令

R语言 常用命令

# 3. 作图

+ geom_abline(slope = 1)+               # 加对角线  geom_text_repel(aes(label=label))+    # library(ggrepel)，点的文本分开  labs(title="",x="",y="")+  scale_x_continuous(breaks = c(1997, 2003, 2008, 2014))+  guides(fill=guide_legend(title=NULL))+ theme_bw()+ theme(legend.position="non")

# 4. 运算

## 4.1 矩阵重复

kronecker(matrix(1, M, N), A) # 矩阵A行方向复制M次、列方向复制N次kronecker(diag(1, N), A)      # 以A为对角元素的对角阵

## 4.2 符号计算

# 微分expFun=expression(a*x^2)                                 # 表达式expFuna=0.5; x=2; eval(expFun)                                 # 求表达式在a=0.5, x=1处的值Fun=as.function(alist(x=, a=0.5, a*x^2))                 # 函数f(x;a=0.5)FunFun(x=2)                                                 # 求函数值f(1)   D1x=D(expFun, "x")                                       # 对表达式中x求一阶偏导D1xD1a=D(expFun, "a")data.frame(x,a,expFun=as.character(expFun),           D1x=eval(D1x), D1a=eval(D1a))DD <- function(expr, name, order){                       # 写函数，循环求高阶导数   if (order < 1)       stop("'order' must be >= 1")   if (order == 1)       D(expr, name) else DD(D(expr, name), name, order - 1)}DD(expFun, "x", 2)                                       # 调用函数求2阶导DD(expFun, "x", 3)NormDensity <- expression(1/sqrt(2 * pi) * exp(-x^2/2))  # 正态密度函数class(NormDensity)D(NormDensity, "x")                                      # 求一阶导数deriv(NormDensity, "x")deriv3(NormDensity, "x")DD(NormDensity, "x", 3)# 积分library(Ryacas)yacas(expression(integrate(1/x, x)))yacas("Integrate(x)1/x")x <- Sym("x"); Integrate(1/x, x)yacas("Integrate(t)a*t")Simplify(yacas("Integrate(t)a*t"))

# 5. 老鼠4*4方格，概率

a=matrix(c(0.6, 0.5, 0, 0.2, 0.5, 1/3, 0, 0.5, 1/3),3,byrow=T)old=rep(1,3)for (i in 1:5){  new=a %*% old  N=t(new)%*%c(4,8,4)  print(data.frame(new, old))  print(N)  old=new} library(expm)print(round(rowSums(a%^%10),3))b=matrix(c(0.6,0.4,0,0.25,0.5,0.25,0,2/3,1/3),3,byrow=T)print(round(colSums(c(4,8,4)%*%b%^%10),3))(b%^%10)[2,]*16/c(4,8,4)

# 参考文献

1. 黄湘云：R语言做符号计算
2. K. Soetaert and T. Petzoldt: CRAN Task View: Differential Equations
3. R.H. Shumway and D.S. Stoffer, 2016: Time Series Analysis and Its Applications: With R Examples(4th ed.), Springer

• 私有
• 公开
• 删除