vector镜湖万象第一章怎么过最后一关怎么过

第一章 R 语言入门R 的历史S 语言在 1980 年代后期在 AT&T 实验室开发; R 项目由 Auckland 大学统计系 Robert Gentleman 和 Ross Ihaka 于 1995 年开始。 它很快得到广泛用户的欢迎,目前由 R 核心发展团队维持,它 是一个由志愿者组成的工作努力的国际团队。 R 的下载登陆 http:www.r-project.org点击 CRAN 得到一批镜像网站 点击镜像网站,比如 Berkeley 选择合适的系统 选择 base下载安装文件选择 packages,下载软件包 R 里面有什么?Packages(每个都有大量数据和可以读写修改的函数/程序)base The R Base Package boot Bootstrap R (S-Plus) Functions (Canty) class Functions for Classification cluster Cluster Analysis Extended Rousseeuw et al. concord Concordance and reliability datasets The R Datasets Package exactRankTests Exact Distributions for Rank and Permutation Tests foreign Read Data Stored by Minitab, S, SAS, SPSS, Stata, Systat, dBase, ... graphics The R Graphics Package grDevices The R Graphics Devices and Support for Colours and Fonts grid The Grid Graphics Package KernSmooth Functions for kernel smoothing for Wand & Jones (1995) lattice Lattice Graphics Interface tools Tools for Package Development utils The R Utils Package MASSMain Package of Venables and Ripley's MASS methodsFormal Methods and Classes mgcvGAMs with GCV smoothness estimation and GAMMs by REML/PQL multtestResampling-based multiple hypothesis testing nlmeLinear and nonlinear mixed effects models nnetFeed-forward Neural Networks and Multinomial Log-Linear Models网上还有许多。 所有这些 Packages 都是在 base 和 stats package 上添加的。 Base, stats 包含所有固有的应用和数据。 而其他的 packages 包 含各统计学家自己发展的方法和数据。 Task Views一定要使用帮助文件! ! 调用 PackagesPackages:libraries 敲 library(),就知道有什么 libraries 了; 缺省 library 是 base.比如要进入 mass,就敲 &library(mass) 每个 library 都有许多数据 在每个 library 敲 data(),就知道有什么数据。 比如敲 data(Titanic),就调出数据 Titanic。 注意:R 语言对大小写敏感! 从网上下载 Packages从 R 上网直接到 CRAN 主页 选择 packages 进入程序包下载界面, 点击按名字排序浏览可供下载的 packages. 在列表中选择需要的 package, 点击进入下载界面,选择合适版本。 最后,在电脑上安装程序包 R 的基本操作(一)赋值和运算z = rnorm(,0.1) median(z) ? 赋值: “=”可以用“&-”代替 x&-z-&y-&w ? 简单数学运算有: +、-、*、/、^、%*%、%%(mod)、 %/%(整数除法)等等。 ? 常用的数学函数有: abs , sign , log , log2, log10 , logb, expm1, log1p(x), sqrt , exp , sin , cos , tan , acos , asin, atan , cosh , sinh,tanh 还有:? ? ? ? ? ? ? ? ? ? ? round, floor, ceiling gamma , lgamma, digamma and trigamma. sum, prod, cumsum, cumprod max, min, cummax, cummin, pmax, pmin, range mean, length, var, duplicated, unique union, intersect, setdiff &、&=、 &、&=、&、|、! 输入输出:scan, read.table, dump, save, load, write, write.table letters, LETTERS list, matrix, array, cbind, rbind, merge sort, order, sort.list, rev, stack, unstack , reshape (二)序列和向量 z=seq(-1,10,length=100) z=seq(-1,10, len=100) z=seq(10,-1,-1) z=10:-1 x=rep(3,1:3) x=rep(3:5,1:3) x=rep(c(1,10),c(4,5)) w=c(1,3,x,z);w[3] (三)分布和产生随机数? 正态分布: pnorm(1.2,2,1);dnorm(1.2,2,1); qnorm(.7,2,1);rnorm(10,0,1)#rnorm(10) ? t 分布: pt(1.2,1);dt(1.2,2);qt(.7,1);rt(10,1) ? 此外还有指数分布、F 分布、 “卡方”分布、Beta 分布、二项分布、 Cauchy 分布、 Gamma 分布、 几何分布、 超几何分布、 对数正态分布、 Logistic 分布、负二项分布、Poisson 分布、均匀分布、Weibull 分布、 Willcoxon 分布等。 ? 变元可以是向量! (四)向量运算? x=rep(0,10);z=1:3;x+z [1] 1 2 3 1 2 3 1 2 3 1 Warning message: longer object length is not a multiple of shorter object length in: x + z x*z [1] 0 0 0 0 0 0 0 0 0 0 Warning message: longer object length is not a multiple of shorter object length in: x * z rev(x) z=c(&no cat&,&has &,&nine&,&tails&) z[1]==&no cat& [1] TRUE?? ? ? (五)向量名字和 appendx=1:3;names(x)=LETTERS[1:3];x AB C 123 append(x,runif(3),after=2) A B C 1......0000000(六)向量赋值z=1:5;z[7]=8;z ? [1] 1 2 3 4 5 NA 8 rnorm(10)[c(2,5)] z[-c(1,3)] #去掉第 1、3 元素. z[(length(z)-4):length(z)] #最后五个元素. (七)向量的大小次序z=sample(1:100,10);z #比较 sample(1:100,10,rep=T) [1] 75 68 28 42 17 21 96 34 69 47 order(z) [1] 5 6 3 8 4 10 2 9 1 7 z[order(z)] [1] 17 21 28 34 42 47 68 69 75 96 sort(z) [1] 17 21 28 34 42 47 68 69 75 96 which(z==max(z))#给出下标? ? ? ? (八)矩阵 1、定义矩阵x=matrix(runif(20),4,5);x[,1] [,2] [,3] [,4] [,5] [1,] 0.....,] 0.....,] 0.....,] 0.....x=matrix(1:20,4,5);x[1,] [2,] [3,] [4,] [,1] 1 2 3 4 [,2] 5 6 7 8 [,3] 9 10 11 12 [,4] 13 14 15 16 [,5] 17 18 19 20x=matrix(1:20,4,5,byrow=T);x[1,] [2,] [3,] [4,] [,1] 1 6 11 16 [,2] [,3] [,4] [,5] 2 3 4 5 7 8 9 10 12 13 14 15 17 18 19 20 2、矩阵的行和列nrow(x); ncol(x);dim(x)#行列数目 x=matrix(rnorm(24),4,6) x[c(2,1),]#第 2 和第 1 行 x[,c(1,3)] #第 1 和第 3 列 x[2,1] #第[2,1]元素 x[x[,1]&0,1] #第 1 列大于 0 的元素 sum(x[,1]&0) #第 1 列大于 0 的元素的个数 sum(x[,1]&=0) #第 1 列不大于 0 的元素的个数 x[,-c(1,3)] #没有第 1、3 列的 x. x[-2,-c(1,3)] #没有第 2 行、第 1、3 列的 x. 3、矩阵/向量的子集 x[x[,1]&0&x[,3]&=1,1]; #第 1 中大于 0 并且相应于第 3 列中小于或等于 1 的元素(“与”) x[x[,2]&0|x[,1]&.51,1] #第 1 中小于.51 或者相应于第 2 列中大于 0 的元素(“或”) x[!x[,2]&.51,1] #第一列中相应于第 2 列中不小于.51 的元素(“非”) ? 逻辑运算:&, &, ==, &=, &=, !=;&, |, ! x=rnorm(10) all(x&0);all(x!=0);any(x&0);(1:10)[x&0] x=sample(1:7,5,rep=T);unique(x) 4、矩阵的转置和逆矩阵x=matrix(runif(9),3,3);x [,1] [,2] [,3] [1,] 0...,] 0...,] 0...6082803 t(x) [,1] [,2] [,3] [1,] 0...,] 0...,] 0...6082803 solve(x) # solve(a,b)可以解 ax=b 方程 [,1] [,2] [,3] [1,] -12...,] -8...,] 23...037986 警告:计算机中的 0 是什么? ? x%*%solve(x) [,1] [,2] [,3] [1,] 1. -9. -3. [2,] 5. 1. 3. [3,] -3. 1. 1. ? 要用线性代数的知识来判断诸如有多少非零特征根等问题。 假定 v 是特征值组成的向量,不能用诸如 sum(v!=0) 等方 法来判断非零特征根的数目! 5、矩阵乘法及行列运算? x=matrix(1:30,5,6);y=matrix(rnorm(20),4,5) ? y%*%x[,1] [,2] [,3] [,4] [,5] [,6] [1,] -3......,] -14....5.0.,] -1......,] 5......453563? apply(x,1,mean) [1] 13.5 14.5 15.5 16.5 17.5 ? apply(x,2,sum) [1] 15 40 65 90 115 140 ? apply(x,2,prod) [1] 120
5600 6、矩阵与向量之间的运算? sweep(x,1,1:5,&*&) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 1 6 11 16 21 26 [2,] 4 14 24 34 44 54 [3,] 9 24 39 54 69 84 [4,] 16 36 56 76 96 116 [5,] 25 50 75 100 125 150 ? x*1:5 ? sweep(x,2,1:6,&+&) [,1] [,2] [,3] [,4] [,5] [,6] [1,] 2 8 14 20 26 32 [2,] 3 9 15 21 27 33 [3,] 4 10 16 22 28 34 [4,] 5 11 17 23 29 35 [5,] 6 12 18 24 30 36 (九)Array 1、Array 与矩阵? x=array(runif(20),c(4,5)); x[,1] [,2] [,3] [,4] [,5] [1,] 0.....,] 0.....,] 0.....,] 0.....7644741? is.matrix(x) [1] TRUE ? x[1,2] ? x[1,];x[,2] ? dim(x) ? x=array(runif(24),c(4,3,2)) ? is.matrix(x) #可由 dim(x)得到维数(4,3,2) [1] FALSE ?x,,1 [,1] [,2] [,3] [1,] 0... [2,] 0... [3,] 0... [4,] 0... ,,2 [,1] [,2] [,3] [1,] 0...,] 0...,] 0...,] 0...7648297 ? x=array(1:24,c(4,3,2)) ? x[c(1,3),,] ,,1 [,1] [,2] [,3] [1,] 1 5 9 [2,] 3 7 11 ,,2 [,1] [,2] [,3] [1,] 13 17 21 [2,] 15 19 23 2、Array 的维运算? x=array(1:24,c(4,3,2)) ? apply(x,1,mean) [1] 11 12 13 14 ? apply(x,1:2,sum) [,1] [,2] [,3] [1,] 14 22 30 [2,] 16 24 32 [3,] 18 26 34 [4,] 20 28 36 ? apply(x,c(1,3),prod) [,1] [,2] [1,] 45 4641 [2,] 120 5544 [3,] 231 6555 [4,] 384 7680 3、Array 和矩阵/向量/array 之间的运算? z=array(1:24,c(2,3,4)) #注意排列次序;z ,,1 [,1] [,2] [,3] [1,] 1 3 5 [2,] 2 4 6 ,,2 [,1] [,2] [,3] [1,] 7 9 11 [2,] 8 10 12 ,,3 [,1] [,2] [,3] [1,] 13 15 17 [2,] 14 16 18 ,,4 [,1] [,2] [,3] [1,] 19 21 23 [2,] 20 22 24 ? sweep(z,1,1:2,&-&),,1 [1,] [2,] ,,2 [1,] [2,] ,,3 [1,] [2,] ,,4 [1,] [2,] [,1] [,2] [,3] 0 2 4 0 2 4 [,1] [,2] [,3] 6 8 10 6 8 10 [,1] [,2] [,3] 12 14 16 12 14 16 [,1] [,2] [,3] 18 20 22 18 20 22 ? sweep(z,c(1,2),matrix(1:6,2,3),&-&),,1 [1,] [2,] ,,2 [1,] [2,] ,,3 [1,] [2,] ,,4 [1,] [2,] [,1] [,2] [,3] 0 0 0 0 0 0 [,1] [,2] [,3] 6 6 6 6 6 6 [,1] [,2] [,3] 12 12 12 12 12 12 [,1] [,2] [,3] 18 18 18 18 18 18 (十)外积? outer(1:2,rep(1,2)) [,1] [,2] [1,] 1 1 [2,] 2 2 ? outer(1:2,matrix(rep(1,6),3,2)) ,,1 [,1] [,2] [,3] [1,] 1 1 1 [2,] 2 2 2 ,,2 [,1] [,2] [,3] [1,] 1 1 1 [2,] 2 2 2 (十一)List(set of objects) ? list 可以是任何对象的集合(包括 lists) ? z=list(1:3,Tom=c(1:2, a=list(&R&,letters[1:5]),w=&hi!&)) ? z[[1]];z[[2]];z$T;z$T$a2;z$T[[3]];z$T$w ? attributes(z)#属性! $names [1] && &Tom& ? attributes(matrix(1:6,2,3)) $dim [1] 2 3 (十二)矩阵,array 及其维名字? x=matrix(1:12,nrow=3,dimnames=list(c(&I&,&II&,&III&),paste(&X&,1:4 ,sep=&&)))I II III X1 X2 1 4 2 5 3 6 X3 X4 7 10 8 11 9 12? y=array(1:12,c(3,2,2),dimnames=list(c(&I&,&II&,&III&),paste(&X&,1:2 sep=&&),paste(&Y&,1:2, sep=&&))) , , Y1 , , Y2 X1 X2 X1 X2 I 1 4 I 7 10 II 2 5 II 8 11 III 3 6 III 9 12 (十三)data.frame? x=matrix(1:6,2,3) ? x=as.data.frame(x);x V1 V2 V3 1 1 3 5 2 2 4 6 ? x$V2 [1] 3 4 ? attributes(x) $names [1] &V1& &V2& &V3& $row.names [1] &1& &2& $class [1] &data.frame& ? names(x)=c(&TOYOTA&,&GM&,&HUNDA&) ? row.names(x)=c(&2001&,&2002&) ?x TOYOTA GM HUNDA
6 ? x$GM [1] 3 4 ? attach(x) ? GM [1] 3 4 ? detach(x) ? GM Error: Object &GM& not found (十四)直接手工输入和编辑数据 ? 直接敲入:x=c(1,2,7,8,…) ? 或者 ? x=scan() ? 1 2 7 8 ….(以“Enter”两次来结束) ? fix(x)(通过编辑修改数据) Categorical data A survey asks people if they smoke or not. The data is Yes, No, No, Yes, Yes? x=c(&Yes&,&No&,&No&,&Yes&,&Yes&) ? table(x);x ? factor(x) ? Barplot: Suppose, a group of 25 people are surveyed as to their beer-drinking preference. The categories were (1) Domestic can, (2) Domestic bottle, (3) Microbrew and (4) import. The raw data is 3 4 1 1 3 4 3 3 1 3 2 1 2 1 2 3 2 3 1 1 1 1 4 3 1? beer = scan() 1 ? barplot(beer) # this isn't correct ? barplot(table(beer)) # Yes, call with summarized data ? barplot(table(beer)/length(beer)) # divide by n for proportion table(beer)/length(beer) ? CEO salaries Suppose, CEO yearly compensations are sampled and the following are found (in millions). (This is before being indicted for cooking the books.) 12 .4 5 2 50 8 3 1 4 0.25? sals = scan() # read in with scan 12 .4 5 2 50 8 3 1 4 0.25 ? mean(sals) ;var(sals) ; sd(sals) ;median(sals) ? fivenum(sals) # min, lower hinge, Median, upper hinge, max ? summary(sals) ? data=c(10, 17, 18, 25, 28,28); summary(data); ? quantile(data,.25); quantile(data,c(.25,.75)) sort(sals); fivenum(sals); summary(sals) mean(sals,trim=1/10) ;mean(sals,trim=2/10) IQR(sals) Mad:median|Xi-median(X)|(1.4826) mad(sals) median(abs(sals - median(sals))) # without median(abs(sals - median(sals))) * 1.4826 Stem-and-leaf Charts: Suppose you have the box score of a basketball game and the following points per game for players on both teams. 2 3 16 23 14 12 4 13 2 0 0 0 6 28 31 14 4 8 2 5scores = scan() 2 3 16 23 14 12 4 13 2 0 0 0 6 28 31 14 4 8 2 5 apropos(&stem&) #`apropos? returns a character vector giving the names of all objects in the search list matching `what?. 如& apropos(“stem”) [1] “stem” “system” “system.file” “system.time” 参看 find(&stem&) stem(scores);stem(scores,scale=2) The salaries could be placed into broad categories of 0-1 million, 1-5 million and over 5 million. To do this using R one uses the cut() function and the table() function. Suppose the salaries are again 12 .4 5 2 50 8 3 1 4 .25. And we want to break that data into the intervals [0; 1]; (1; 5]; (5; 50]sals = c(12, .4, 5, 2, 50, 8, 3, 1, 4, .25) # enter data cats = cut(sals,breaks=c(0,1,5,max(sals))) # the breaks cats # view the values table(cats) # organize levels(cats) = c(&poor&,&rich&,&rolling in it&) table(cats) Histograms:Suppose the top 25 ranked movies made the following gross receipts for a week 4 29.6 28.2 19.6 13.7 13.0 7.8 3.4 2.0 1.9 1.0 0.7 0.4 0.4 0.3 0.3 0.3 0.3 0.3 0.2 0.2 0.2 0.1 0.1 0.1 0.1 0.1 x=scan() 29.6 28.2 19.6 13.7 13.0 7.8 3.4 2.0 1.9 1.0 0.7 0.4 0.4 0.3 0.3 0.3 0.3 0.3 0.2 0.2 0.2 0.1 0.1 0.1 0.1 0.1 hist(x) # frequencies hist(x,probability=TRUE) # proportions (or probabilities) rug(jitter(x)) # add tick marks hist(x,breaks=10) # 10 breaks, or just hist(x,10) hist(x,breaks=c(0,1,2,3,4,5,10,20,max(x))) # breaks Frequency Polygons:x = c(.314,.289,.282,.279,.275,.267,.266,.265,.256,.250,.249,.211,.161) tmp = hist(x) # store the results lines(c(min(tmp$breaks),tmp$mids,max(tmp$breaks)),c(0,tmp$counts,0), type=&l&) ? ? ? ?data(faithful) attach(faithful) # make eruptions visible hist(eruptions,15,prob=T) # proportions, not frequencies lines(density(eruptions)) # lines makes a curve, default bandwidth Handling bivariate categorical data: Person Smokes amount of Studying1 Y less than 5 hours 2 N 5 - 10 hours 3 N 5 - 10 hours 4 Y more than 10 hours 5 N more than 10 hours 6 Y less than 5 hours 7 Y 5 - 10 hours 8 Y less than 5 hours 9 N more than 5 hours 10 Y 5 - 10 hours library(MASS) quine attach(quine) table(Age) table(Sex, Age); tab=xtabs(~ Sex + Age, quine); unclass(tab) tapply(Days, Age, mean) tapply(Days, list(Sex, Age), mean) apply, sapply, tapply, lapply ? ? ? ? ? ? ?smokes = c(&Y&,&N&,&N&,&Y&,&N&,&Y&,&Y&,&Y&,&N&,&Y&) amount = c(1,2,2,3,3,1,2,1,3,2) table(smokes,amount) tmp=table(smokes,amount) # store the table options(digits=3) # only print 3 decimal places prop.table(tmp,1) # the rows sum to 1 now prop.table(tmp,2) # the columns sum to 1 now Really ?sweep(x, margin, margin.table(x, margin), &/&)? ? prop.table(tmp) #amount # all the numbers sum to 1 ? options(digits=7) # restore the number of digits Plotting tabular data ? ? ? ? ? barplot(table(smokes,amount)) barplot(table(amount,smokes)) smokes=factor(smokes) # for names barplot(table(smokes,amount), beside=TRUE, legend.text=T) barplot(table(amount,smokes),main=&table(amount,smokes)&, beside=TRUE, legend.text=c(&less than 5&,&5-10&,&more than 10&)) categorical vs. numerical:A simple example might be in a drug test, where you have data (in suitable units) for an experimental group and for a control group. experimental: 5 5 5 13 7 11 11 9 8 9 control: 11 8 4 5 9 5 10 5 4 10 ? ? ? ? ? ? ? x = c(5, 5, 5, 13, 7, 11, 11, 9, 8, 9) y = c(11, 8, 4, 5, 9, 5, 10, 5, 4, 10) boxplot(x,y);amount = scan() 5 5 5 13 7 11 11 9 8 9 11 8 4 5 9 5 10 5 4 10 category = scan()
boxplot(amount ~ category) # note the tilde ~ (十五)从文本文件输入 ASCII 码数据 ? x=scan(&f:\\book\\1.txt&) 这是按照文本一行一行读入的数据 如果原先是 4*5 矩阵形式,则加用 ? x=matrix(x,4,5,byrow=T)或直接用 ? x= matrix(scan(&f:\\book\\1.txt&),4,5,b=T) 如果原先是 4*5 有名字的 data.frame 形式,则用 ? x=read.table(&f:\\book\\ww.txt&,header=T) ?xGM VW HUNDA
8 (十六)控制语句? ? ? ? ? x=NULL;for(i in 1:5)x=cbind(x,i^2) i=1;x=NULL;while(i&=5){x=cbind(x,i^2);i=i+1} x=rnorm(1);if (x&0) y=x else y=-x+10 i=1;x=rnorm(1); repeat{x=x+rnorm(1);if(x&3)i=i+1};print(c(i,x)) (十七)by attach(warpbreaks) by(warpbreaks[, 1:2], tension, summary) by(warpbreaks[, 1], list(wool = wool, tension = tension), summary) ## now suppose we want to extract the coefficients by group tmp &- by(warpbreaks, tension, function(x) lm(breaks ~ wool, data = x)) sapply(tmp, coef) (十八)%in%和 match## The intersection of two sets : intersect &- function(x, y) y[match(x, y, nomatch = 0)] intersect(1:10,7:20) 1:10 %in% c(1,3,5,9) sstr &- c(&c&,&ab&,&B&,&bba&,&c&,&@&,&bla&,&a&,&Ba&,&%&) sstr[sstr %in% c(letters,LETTERS)] &%w/o%& &- function(x,y) x[!x %in% y] #-- x without y (1:10) %w/o% c(3,7,12) intersect &- function(x, y) y[match(x, y, nomatch = 0)] intersect(1:10,7:20) attach(warpbreaks) warpbreaks[tension%in% c(&L&,&H&),] warpbreaks[warpbreaks$tension%in% c(&L&,&H&),] warpbreaks[warpbreaks[,3]%in% c(&L&,&H&),] unique(tension) (十九) ftable: array/矩阵 把 (没有频率) 数据变成列联表 (计数)## Start with a contingency table. ftable(Titanic, row.vars = 1:3) ftable(Titanic, row.vars = 1:2, col.vars = “Survived”) ftable(Titanic, row.vars = 2:1, col.vars = “Survived”) ## Start with a data frame. x &- ftable(mtcars[c(“cyl”, “vs”, “am”, “gear”)]) x #为 array,其维的次序为(“cyl”, “vs”, “am”, “gear”) ftable(x, row.vars = c(2, 4))#从 x(array)确定表的行变量 ## Start with expressions, use table()'s &dnn& to change labels ftable(mtcars$cyl, mtcars$vs, mtcars$am, mtcars$gear, row.vars = c(2, 4), dnn = c(&Cylinders&, &V/S&, &Transmission&, &Gears&)) ftable(vs~carb,mtcars) #vs 是列,carb 是行#或 ftable(mtcars$vs~mtcars$carb) ftable(carb~vs,mtcars) #vs 是行,carb 是列 ftable(mtcars[,c(8,11)]) #和上面 ftable(carb~vs,mtcars)等价 ftable(breaks~wool+tension,warpbreaks) (二十)as.data.frame(UCBAdmissions) 把 array(三维)变成方阵 DF &- as.data.frame(UCBAdmissions) Admit Gender Dept Freq 1 Admitted Male A 512 2 Rejected Male A 313 (二十一)xtabs(Freq ~ Gender + Admit, DF) 把有频率/计数方阵变成列联表 a=xtabs( Freq~ Admit + Gender, data=DF)#如无频数(权), 左边为空 Gender Admit Male Female Admitted
library(MASS);biplot(corresp(a, nf=2)) #应用之一 上一页数据中变量的属性和定量标签的互换 ? is.factor(DF[,2]) [1] TRUE ? is.factor(DF[,3]) [1] TRUE ? is.factor(DF[,4]) [1] FALSE ? DF[,4]=as.factor(DF[,4]) ? is.factor(DF[,4]) [1] TRUE ? DF[,4]=as.numeric(DF[,4]) ? is.factor(DF[,4]) [1] FALSE (二十二)as.factor 用哑元记录属性变量观测时,如不改变标签,则可能出错mtcars[1:4,]mpg cyl disp hp drat wt qsec vs am gear carb Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1lm(mpg~gear+carb,mtcars) #把定性变量当成定量变量Call: lm(formula = mpg ~ gear + carb, data = mtcars) Coefficients: (Intercept) gear carb 7.276 5.576 -2.754 mtcars[,10]=as.factor(mtcars[,10]) #改变标签 mtcars[,11]=as.factor(mtcars[,11]) #改变标签 lm(mpg~gear+carb,mtcars)Call: lm(formula = mpg ~ gear + carb, data = mtcars) Coefficients: (Intercept) gear4 gear5 carb2 carb3 20.932 7.720 8.349 -3.289 -4.632carb4 carb6 carb8 -9.064 -9.581 -14.281(二十三)向量比较:all x=1:12; y=1:12; all(y==x)[1] TRUE (二十四)cat 和 print& if(all(x & 0)) cat(&all x values are negative\n&) all x values are negative & cat(&a logical or (positive) numeric controlling how the output is + broken into successive lines. If 'FALSE' (default), only + newlines created explicitly by\n&) a logical or (positive) numeric controlling how the output is broken into successive lines. If 'FALSE' (default), only newlines created explicitly by & if(all(x & 0)) print(&all x values are negative\n&) [1] &all x values are negative\n& & print(&a logical or (positive) numeric controlling how the output is + broken into successive lines. If 'FALSE' (default), only + newlines created explicitly by&) [1] &a logical or (positive) numeric controlling how the output is\n broken into successive lines. If 'FALSE' (default), only\n newlines created explicitly by& 解释后面语句的意思n=1200;x=runif(n*10) x=matrix(x,n,10) x1=(x[,1:5]&.4)*1 p=x1*.8+(1-x1)*.2 x2=1*(x[,6:10]&p) z=cbind(x1,x2) ss=function(z){nu=NULL;pattern=NULL z0 =as.matrix(z);n=nrow(z0);id=1; repeat{if (id%%100==0)print(id) z1=sweep(z0,2,z0[1,],&==&) pattern=rbind(pattern,z0[1,]) z2=apply(z1,1,prod) z0=z0[z2!=1,];nu=c(nu,sum(z2)) if (sum(nu)&=n)break if (is.matrix(z0)==F) {nu=c(nu,1);pattern=rbind(pattern,z0);id=id+1 break} id=id+1} list(pattern=pattern,number=nu,id=id) } R 语言画图x=0:18 plot(x,x,pch=x,col=x) points(x,18-x,pch=x) matplot(x,cbind(x,18-x))spring= data.frame(compression=c(41,39,43,53,42,48,47,46), distance=c(120,114,132,157,122,144,137,141)) attach(spring) (Hooke?s law: f=.5ks) plot(distance ~ compression) plot(compression, distance) ? par(mfrow=c(2,2)) #准备画 2? 的 4 个图 2 ? plot(compression, distance,main= &Hooke's Law&) #只有标题的图 ? plot(compression, distance,main= &Hooke's Law&, xlab= &x&,ylab= &y&) #标题+x,y 标记 ? identify(compression,distance) #标出点号码 ? plot(compression, distance,main=&Hooke's Law&) #只有标题的图 ? text(46,120, &f=1/2*k*s&) #在指定位写入文字 ? plot(compression, distance,main=&Hooke's Law&) #只有标题的图 ? text(locator(2), &I am here!&) #在点击的两个位置写入文字 Hooke's LawHooke's Law 4150150140distancey1408 3 761301301201205 240142 44 46 x 48 50 5240424446 compression485052Hooke's LawHooke's Law150140distancedistance140150I am here!I am here!130120f=1/2*k*s40424446 compression48505212013040424446 compression485052 ? library(mass); ? data(Animals); ? attach(Animals) ? plot(body, brain) ? plot(sqrt(body), sqrt(brain)) ? plot((body)^0.1, (brain)^0.1) ? plot(log(body),log(brain)) 5000sqrt(brain)0
body brain3000010000020406050100150 sqrt(body)2002503002.0(brain)^0.1log(brain)1.0 1.5 2.0 (body)^0.1 2.5 3.01.51.00246805 log(body)10 1、原始数据 ? par(mfrow=c(1,1), pch=1) ? plot(body, brain, xlim=c(0, 6000)) ? text(x=body, y=brain,labels=row.names(Animals), adj=0) # adj=0 implies left adjusted text 2、几个点 ? plot(body[c(1,3,8)], brain[c(1,3,8)],xlim=c(0,200)) ? text(x=body[c(1,3,8)],y=brain[c(1,3,8)],labels=row.names(Anima ls[,c(1,3,8)]), adj=0) 5000Asian elephant4000 brain 1000Human Giraffe Horse Chimpanzee Donkey Cow Gorilla Rhesus monkey Sheep Pig Jaguar Grey Potar wolf Goat monkey Kangaroo Golden hamster Guinea pig Mountain beaver Cat Mole Rabbit Rat Mouse 0 00 body 0001 brain[c(1, 3, 8)]200300400Grey wolf100Cow0Mountain beaver 0 50 100 body[c(1, 3, 8)] 150 2002 3、对数变换 ? Par(cex=0.7,mex=0.7) #character (cex) & margin (mex) expansion ? plot(log(body),log(brain)) ? text(x=log(body), y=log(brain),labels=row.names(Animals), adj=1.5) # adj=0 implies left adjusted text 4、按照次序 ? plot(log(body),log(brain)) ? identify(log(body),log(brain),row.names(Animals)) African elephant Asian elephant8Human Chimpanzee Giraffe Horse Donkey Cow Gorilla Pig Brachiosaurus Triceratops Dipliodocus6log(brain)Rhesus monkey Sheep Jaguar wolf Potar monkey GreyGoat Kangaroo Cat Rabbit Mountain beaver Guinea pig Mole Rat2 4Golden hamster Mouse 0 log(body) 5 1003 Asian elephant8African elephantHuman Giraffe Horse Chimpanzee Donkey Gorilla Cow Rhesus monkeylog(brain)6Pig Sheep Jaguar Grey wolf Goat Potar monkey KangarooBrachiosaurus Triceratops Dipliodocus4Cat Mountain beaver Rabbit Mole Guinea pig Rat02Golden hamster Mouse 0 log(body) 5 104 ? plot(1,1,xlim=c(1,7.5),ylim=c(0,5),type=&n&) # Do not plot points ? points(1:7,rep(4.5,7),cex=1:7,col=1:7, pch=0:6) ? text(1:7,rep(3.5,7),labels=paste(0:6,letters[1:7]),cex=1:7, col=1:7)5 40a31b2c3 d4e5f6 g1 0 1 21234 1567 ? points(1:7,rep(2,7), pch=(0:6)+7) # Plot symbols 7 to 13 ? text((1:7)+0.25, rep(2,7), paste((0:6)+7)) # Label with symbol number ? points(1:7,rep(1,7), pch=(0:6)+14) # Plot symbols 14 to 20 ? text((1:7)+0.25, rep(1,7), paste((0:6)+14)) # Labels with symbol number 450a31b2c8 93 d410e5 f 611 12 18 19g13 201 2711415161701234 1567 R 语言函数例子:中位数和均值的比值函数 用该函数计算一万个(均值为 1 的)指数分布的中位数和均值的比 median.mean.ratio &- function(x) { return(median(x)/mean(x)) } z &- rexp(10000) median.mean.ratio(z) 在函数中的{}中间,可以有多个语句;语句之间用换行或分号(;)分开. 函数的编辑? fix(median.mean.ratio) ? 这时会出现一个记事本编辑器 ? 编辑并试图存了之后如果发生错误(不会存),往往会让你编辑改 过但有语法错误的 fix(); ? 如果还使用 fix(median.mean.ratio)则是编辑以前的版本。 ? 函数可以有缺省值,例如 ? Expo=function(y,x=2) {z=y^x;z} ? y=seq(0,1,length=100); ? plot(y,Expo(y),type=&l&) 函数可以不写 return,这时最后一个值为 return 的值。 为了输出多个值最好使用 list。 颜色画图函数? ? ? ? ? ? ? ? ? ? ? ? view.colours = function(){ plot(1, 1, xlim=c(0,14), ylim=c(0,3), type=&n&, axes=F, xlab=&&,ylab=&&) text(1:6, rep(2.5,6), paste(1:6), col=palette()[1:6], cex=2.5) text(10, 2.5, &Default palette&, adj=0) rainchars = c(&R&,&O&,&Y&,&G&,&B&,&I&,&V&) text(1:7, rep(1.5,7), rainchars, col=rainbow(7), cex=2.5) text(10, 1.5, &rainbow(7)&, adj=0) cmtxt = substring(&cm.colors&, 1:9,1:9) # Split &cm.colors& into its 9 characters text(1:9, rep(0.5,9), cmtxt, col=cm.colors(9), cex=3) text(10, 0.5, &cm.colors(9)&, adj=0) } view.colours() 1 2 3 4 5 6Default paletteR O Y G B I Vrainbow(7)cm . c o l o r scm.colors(9) ? ? ? ?attach(spring);spring row.names(spring)=LETTERS[1:8] ;spring plot(distance,compression) identify(distance,compression,row.names(spring))52D5048F Gcompression46H44C42E40A B 120 130 distance 140 150 ? par(mfrow=c(1,2)) ? plot(x&-0:50, y&-pi*x^2, xlab=&Radius&, ylab=expression(Area == pi*r^2),type=&b&) ? plot(x&-0:50, y&-pi*x^2,xlab=&Radius&, ylab=&Area == pi*r^2&,type=&l&) #What is the difference? ? par(mfrow=c(1,1)) Area 00 10 20 30 40 50 Radiusr 60002200040008000Area == pi*r^2 00 10 20 Radius 30 40 502000400060008000 ? ? ? ? ? ? ?par(mfrow=c(2,2)) plot(1:10,1:10,main=&Straight line&,type=&l&) locator(n=2,type=&l&)#加一条 n 个点决定的折线 hist(rnorm(50), main=&Histogram of Normal&) qqnorm(rt(100,2), main=&Samples from t(2)&) plot(density(rnorm(50)), main=&Normal density&) par(mfrow=c(1,1)) Straight line10 12Histogram of Normal8Frequency1:1064224 1:1068100246810-2-10 rnorm(50)12Samples from t(2)4 0.4Normal densitySample QuantilesDensity0-2-4-2-10120.0-60.10.20.32-2024Theoretical QuantilesN = 50 Bandwidth = 0.4335 ? plot(complex(arg=seq(-pi,pi,len=20)),main=&Complex numbers&, sub=&circle&)Complex numbers1.0 Im(complex(arg = seq(-pi, pi, len = 20))) -1.0-1.0-0.50.00.5-0.50.0 Re(complex(arg = seq(-pi, pi, len = 20))) circle0.51.0 时间序列画图? x=runif(100);x=ts(x,start=),frequency=12);options(digits=2);x ? plot(x,main=&Time series&) Time series1.0 x 0.0 0.2 0.4 0.6 0.8196019621964 Time19661968 Matplot? sines=outer(1:20,1:4,function(x, y) sin(x / 20 * pi * y)) ? matplot(sines, pch = 1:4, type = &o&, col = rainbow(ncol(sines))) sines -1.0 -0.5 0.0 0.5 1.05 10 15 20 ? x &- 0:50/50 ? matplot(x, outer(x, 1:8, function(x, k) sin(k*pi * x)), ylim = c(-2,2), type = &plobcsSh&, main= &matplot(,type = \&plobcsSh\& )&)matplot(,type = &plobcsSh& )2 outer(x, 1:8, function(x, k) sin(k * pi * x)) 1 -20.0 4
3 111 11 3 43 4 11 11 3 3 4 311 4 11 43 4 3 113 3 11 4 1 4 11 3 43 11 3 4 3 11 3 11 4 4 3 3 11 3 4 111 4 31 113 4 3 3 4 11 4 3 11 4 3 4 3 3 4 4 3 4 3 4 4 4 3 3 4 4 4 3 3 4 4 34 3 4 4 43 3 4 4 4 33 33 444 444 3-100.20.4 x0.60.81.0 符号和线条类型? par(mfrow=c(1,1)) ? plot(1:10,sin(1:10),lty=1,pch=2,type=&b&)1.0 sin(1:10) -1.0 -0.5 0.0 0.524 1:106810 Legend? ? ? ? ? x &- seq(-pi, pi, len = 65) plot(x, sin(x), type = &l&, ylim = c(-1.2, 1.8), col = 3, lty = 2) points(x, cos(x), pch = 3, col = 4) lines(x, tan(x), type = &b&, lty = 1, pch = 4, col = 6) title(&legend(..., lty = c(2, -1, 1), pch = c(-1,3,4), merge = TRUE)&, cex.main = 1.1) ? legend(-1, 1.9, c(&sin&, &cos&, &tan&), col = c(3,4,6), lty = c(2, -1, 1), pch = c(-1, 3, 4), merge = TRUE, bg='gray90') legend(..., lty = c(2, -1, 1), pch = c(-1,3,4), merge = TRUE)sin(x)-1.0-0.50.00.51.01.5sin cos tan-3-2-10 x123 Table 和 barplot、pie? tN &- table(Ni &- rpois(100, lambda=5));tN 0 1 2 3 4 5 6 7 8 9 11 12 1 7 12 14 16 14 19 9 4 2 1 1 ? r &- barplot(tN, col='gray')05101501234567891112 ? lines(r, tN, type='h', col='red', lwd=2) #- type = &h& plotting *is* `bar'plot05101501234567891112 ? barplot(tN, space = 1.5, axisnames=FALSE, sub = &barplot(..., space=0, axisnames = FALSE)&) #如 space=1.5 则有稀牙缝051015barplot(..., space= 1.5, axisnames = FALSE) ? pie(tN)3 24 1 0 12 11 9 5 876 Boxplot? ? ? ? ? ? ? ? ? par(mfrow=c(2,1)) data(faithful) # read in data set names(faithful) attach(faithful) # to access the names above boxplot(waiting,main=&Waiting time&,horizontal=TRUE) boxplot(eruptions, main=&Eruptions&,horizontal=TRUE) detach(faithful) # tidy up par(mfrow=c(1,1)) ? data(ToothGrowth) ? boxplot(len ~ dose, data = ToothGrowth, boxwex = 0.25, at = 1:3 - 0.2, subset= supp == &VC&, col=&yellow&, main=&Guinea Pigs' Tooth Growth&, xlab=&Vitamin C dose mg&, ylab=&tooth length&, ylim=c(0,35)) ? boxplot(len ~ dose, data = ToothGrowth, add = TRUE, boxwex = 0.25, at = 1:3 + 0.2, subset= supp == &OJ&, col=&orange&) ? legend(2, 9, c(&Ascorbic acid&, &Orange juice&), fill = c(&yellow&, &orange&)) ? 作了两个图叠加,一个为 subset= supp == “VC“,另一个为 subset= supp == ”OJ“.数据 ToothGrowth 有两个数量变量(len,dose)和一个属性变量 (supp);对每个 supp,dose 各有三个值(各形成三个盒形图). len ~ dose 意 味着 box 为 len 所做. Guinea Pigs' Tooth Growth35 tooth length 10 15 20 25 30Ascorbic acid Orange juice5 00.50.51122Vitamin C dose mg QQ 图? par(mfrow=c(1,3)) ? y &- rt(200, df = 5) ? qqnorm(y); qqline(y, col = 2) #和正态分布比 ? qqplot(y, rt(300, df = 5)); #和 t(5)分布比 ? data(precip) ? qqnorm(precip, ylab = “Precipitation [in/yr] for 70 US cities”); qqline(precip,col=3) #和正态分布比 ? par(mfrow=c(1,1)) Normal Q-Q PlotNormal Q-Q Plot4422Precipitation [in/yr] for 70 US cities-4 -2 0 y 2 4Sample Quantilesrt(300, df = 5)00-2-2-4-3-2-10123102030405060-2-1012Theoretical QuantilesTheoretical Quantiles Pairs? data(iris) ? pairs(iris[1:4], main = &Anderson's Iris Data -- 3 species&, pch = 21, bg = c(&red&, &green3&, &blue&)[codes(iris$Species)]) #iris 为 150? 数据,这里是 4 个数量变量的点图(最后一个是分类 5 变量(iris$Species)) Anderson's Iris Data -- 3 species2.0 2.5 3.0 3.5 4.0 0.5 1.0 1.5 2.0 2.57.5Sepal.Length2.0 2.5 3.0 3.5 4.0Sepal.WidthPetal.Length0.5 1.0 1.5 2.0 2.5Petal.Width4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0123456712345674.55.56.5 Stars? data(mtcars) ? stars(mtcars[, 1:7], key.loc = c(14, 1.5), main = &Motor Trend Cars : full stars()&,flip.labels=FALSE) #mtcars 为 32? 数据,这里只选前 7 个数量变量的点图 11 Motor Trend Cars : full stars()Mazda RX4 Mazda RX4 Wag Datsun 710Hornet 4 Drive Hornet SportaboutValiantDuster 360Merc 240DMerc 230Merc 280Merc 280CMerc 450SEMerc 450SLMerc 450SLC Cadillac Fleetwood Lincoln Continental Chrysler ImperialFiat 128Honda CivicToyota Corolla Toyota Corona Dodge Challenger AMC JavelinCamaro Z28Pontiac FirebirdFiat X1-9Porsche 914-2Lotus Europa Ford Pantera LFerrari Dino disp hp mpg cylMaserati BoraVolvo 142Edrat wt qsec Persp(三维图)? x &- seq(-10, 10, length= 30) ? y &- x ? f &- function(x,y) { r &- sqrt(x^2+y^2); 10 * sin(r)/r } ? z &- outer(x, y, f) ? z[is.na(z)] &- 1 ? persp(x, y, z, theta = 30, phi = 30, expand = 0.5, col = &lightblue&) xyz ? data(volcano) ? z &- 2 * volcano# Exaggerate the relief ? x &- 10 * (1:nrow(z)) #10 meter spacing(S to N) ? y &- 10 * (1:ncol(z)) #10 meter spacing(E to W) ## Don't draw the grid lines : border = NA ? par(bg = &slategray&) ? persp(x, y, z, theta = 135, phi = 30, col = &green3&, scale = FALSE, ? ltheta = -120, shade = 0.75, border = NA, box = FALSE) ? par(bg= &white&) #mtcars 为 87? 数据,作为高度 z. 61
Contour? x &- y &- seq(-4*pi, 4*pi, len = 27) ? r &- sqrt(outer(x^2, y^2, &+&)) ? opar &- par(mfrow = c(2, 2), mar = rep(0, 4)) ? for(f in pi^(0:3)) contour(cos(r^2)*exp(-r/f), ? drawlabels = FALSE, axes = FALSE, frame = TRUE)
? ? ? ? ? ? ? ? ? ?data(&volcano&) rx &- range(x &- 10*1:nrow(volcano)) ry &- range(y &- 10*1:ncol(volcano)) ry &- ry + c(-1,1) * (diff(rx) - diff(ry))/2 tcol &- terrain.colors(12) par(opar); opar &- par(pty = &s&, bg = &lightcyan&) plot(x = 0, y = 0,type = &n&, xlim = rx, ylim = ry, xlab = &&, ylab = &&) u &- par(&usr&) rect(u[1], u[3], u[2], u[4], col = tcol[8], border = “red”) #rect 画矩形 contour(x, y, volcano, col = tcol[2], lty = &solid&, add = TRUE, vfont = c(&sans serif&, &plain&)) ? title(&A Topographic Map of Maunga Whau&, font = 4) ? abline(h = 200*0:4, v = 200*0:4, col = &lightgray&, lty = 2, lwd = 0.1);par(opar) A Topographic Map of Maunga Whau02004006000200400600800 Image? data(volcano) ? x &- 10*(1:nrow(volcano)) ? y &- 10*(1:ncol(volcano)) ? image(x, y, volcano, col = terrain.colors(100), axes = FALSE) ? contour(x, y, volcano, levels = seq(90, 200, by=5), add = TRUE, col = &peru&) ? axis(1, at = seq(100, 800, by = 100)) ? axis(2, at = seq(100, 600, by = 100)) ? box() ? title(main = &Maunga Whau Volcano&, font.main = 4) M aunga Whau Volcano600 100 200 300 y 400 500100200300400 x500600700800 箭头和线段? x=runif(12);y=rnorm(12);I=order(x,y);x=x[i];y=y[i];plot(x,y, main=&arrows(.) and segments(.)&) ## draw arrows from point to point : ? s=seq(length(x)-1) # one shorter than data ? arrows(x[s],y[s],x[s+1],y[s+1],col= 1:3) ? s=s[-length(s)];segments(x[s],y[s], x[s+2],y[s+2],col='pink') 第一部分画点,第二部分画箭头,第三部分画线段 arrows(.) and segments(.)-1.5-1.0-0.50.0y0.51.01.50.20.4 x0.60.8 demo(graphics)? if (dev.cur() &= 1) get(getOption(&device&))() ? opar &- par(ask = interactive() && (.Device %in% c(&X11&, &GTK&, &gnome&, &windows&, &Macintosh&))) ? x &- rnorm(50) ? opar &- c(opar, par(bg = &white&)) ? plot(x, ann = FALSE, type = “n”) #出现“Hit &Return& to see next plot:” ? `ann' If set to `FALSE', high-level plotting functions do not annotate the plots they produce with axis and overall titles. The default is to do annotation. ? abline(h = 0, col = gray(0.9)) ? lines(x, col = &green4&, lty = &dotted&) ? points(x, bg = &limegreen&, pch = 21) ? title(main = &Simple Use of Color In a Plot&, xlab = &Just a Whisper of a Label&, ? col.main = &blue&, col.lab = gray(0.8), cex.main = 1.2, cex.lab = 1, font.main = 4, font.lab = 3) Simple Use of Color In a Plot2 -2 -1 0 101020304050Just a Whisper of a Label ? par(bg = &gray&) ? pie(rep(1, 24), col = rainbow(24), radius = 0.9) #Hit &Return& to see next plot: ? title(main = &A Sample Color Wheel&, cex.main = 1.4, font.main = 3) ? title(xlab = &(Use this as a test of monitor linearity)&, cex.lab = 0.8, font.lab = 3) ? pie.sales &- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12) ? names(pie.sales) &- c(&Blueberry&, &Cherry&, &Apple&, &Boston Cream&, &Other&, &Vanilla Cream&) ? pie(pie.sales, col = c(&purple&, &violetred1&, &green3&, &cornsilk&, &cyan&, &white&)) A Sample Color Wheel7 8 9 10 11 6 5 4 3 2121132414 15 16 17 18 19 20 21 2223(Use this as a test of monitor linearity) ? pie.sales &- c(0.12, 0.3, 0.26, 0.16, 0.04, 0.12) ? names(pie.sales) &- c(&Blueberry&, &Cherry&, &Apple&, &Boston Cream&, &Other&, &Vanilla Cream&) ? pie(pie.sales, col = c(&purple&, &violetred1&, &green3&, &cornsilk&, &cyan&, &white&))#Hit &Return& to see next plot: ? title(main = &January Pie Sales&, cex.main = 1.8, font.main = 1) ? title(xlab = &(Don't try this at home kids)&, cex.lab = 0.8, font.lab = 3) January Pie SalesCherryBlueberryAppleVanilla CreamOther Boston Cream(Don't try this at home k ids) ? par(bg = &cornsilk&) ? n &- 10 ? g &- gl(n, 100, n * 100) ? x &- rnorm(n * 100) + sqrt(codes(g)) ? boxplot(split(x, g), col = &lavender&, notch = TRUE) #Hit &Return& to see next plot: ? title(main = &Notched Boxplots&, xlab = &Group&, font.main = 4, font.lab = 1) Notched Boxplots024612345 Group678910 ? par(bg = &white&) ? n &- 100 ? x &- c(0, cumsum(rnorm(n))) ? y &- c(0, cumsum(rnorm(n))) ? xx &- c(0:n, n:0) ? yy &- c(x, rev(y)) ? plot(xx, yy, type = &n&, xlab = &Time&, ylab = &Distance&) #Hit &Return& to see next plot: ? polygon(xx, yy, col = &gray&) ? title(&Distance Between Brownian Motions&) Distance Between Brownian MotionsDistance -5 051002040 Time6080100 ? x &- c(0, 0.4, 0.86, 0.85, 0.69, 0.48, 0.54, 1.09,1.11, 1.73, 2.05, 2.02) ? par(bg = &lightgray&) ? plot(x, type = &n&, axes = FALSE, ann = FALSE) #Hit &Return& to see next plot: ? usr &- par(&usr&) ? rect(usr[1], usr[3], usr[2], usr[4], col = &cornsilk&, border = &black&) ? lines(x, col = &blue&) ? points(x, pch = 21, bg = &lightcyan&, cex = 1.25) ? axis(2, col.axis = &blue&, las = 1) ? axis(1, at = 1:12, lab = month.abb, col.axis = &blue&) ? box() ? title(main = &The Level of Interest in R&, font.main = 4, col.main = &red&) ? title(xlab = &1996&, col.lab = &red&) The Level of Interest in R2.01.51.00.50.0 Jan Feb Mar Apr May Jun 1996 Jul Aug Sep Oct Nov Dec ? par(bg = &cornsilk&) ? x &- rnorm(1000) ? hist(x, xlim = range(-4, 4, x), col = &lavender&, main = &&) #Hit &Return& to see next plot: ? title(main = &1000 Normal Random Variates&, font.main = 3) 1000 Normal Random Variates200 Frequency 0 50 100 150-4-20 x24 ? data(&iris&) ? pairs(iris[1:4], main = &Edgar Anderson's Iris Data&, font.main = 4, pch = 19)Edgar Anderson's Iris Data2.0 2.5 3.0 3.5 4.0 0.5 1.0 1.5 2.0 2.57.5Sepal.Length2.0 2.5 3.0 3.5 4.0Sepal.WidthPetal.Length0.5 1.0 1.5 2.0 2.5Petal.Width4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0123456712345674.55.56.5 ? pairs(iris[1:4], main = &Edgar Anderson's Iris Data&, pch = 21, bg = c(&red&, &green3&, &blue&)[codes(iris$Species)])Edgar Anderson's Iris Data2.0 2.5 3.0 3.5 4.0 0.5 1.0 1.5 2.0 2.57.5Sepal.Length2.0 2.5 3.0 3.5 4.0Sepal.WidthPetal.Length0.5 1.0 1.5 2.0 2.5Petal.Width4.5 5.0 5.5 6.0 6.5 7.0 7.5 8.0123456712345674.55.56.5 ? data(&volcano&);x &- 10 * 1:nrow(volcano);y &- 10 * 1:ncol(volcano); l &- pretty(range(volcano), 10);par(bg = &lightcyan&);pin &- par(&pin&) ? xdelta &- diff(range(x));ydelta &- diff(range(y)) ? xscale &- pin[1]/yscale &- pin[2]/ydelta ? scale &- if (xscale & yscale) xscale else yscale ? xadd &- 0.5 * (pin[1]/scale - xdelta) ? yadd &- 0.5 * (pin[2]/scale - ydelta) ? plot(numeric(0), numeric(0), xlim = range(x) + c(-1, 1) * xadd, ylim = range(y) + c(-1, 1) * yadd, type = &n&, ann = FALSE) ? usr &- par(&usr&) ? rect(usr[1], usr[3], usr[2], usr[4], col = &green3&) ? contour(x, y, volcano, levels = l, col = &yellow&, lty = &solid&, add = TRUE);box() ? title(&A Topographic Map of Maunga Whau&, font = 4) ? title(xlab = &Meters North&, ylab = &Meters West&, font = 3) ? mtext(&10 Meter Contour Spacing&, side = 3, line = 0.35, outer = FALSE, at = mean(par(&usr&)[1:2]), cex = 0.7, font = 3) A Topographic Map of Maunga Whau10 Meter Contour SpacingMeters West01002003004005006000200400 Meters North600800 ? par(bg = &cornsilk&) ? data(quakes) ? coplot(lat ~ long | depth, data = quakes, pch = 21, bg = &green3&) #Hit &Return& to see next plot: Given : depth100 200 300 400 500 600165170175180185165170175180185-10lat-35-30-25-20-15-10165170175180185long-35-30-25-20-15 example(plotmath)? example(plotmath)#不用这个,等同于下面的语句 ? x &- seq(-4, 4, len = 101) ? y &- cbind(sin(x), cos(x)) ? matplot(x, y, type = &l&, xaxt = &n&, main = expression(paste(plain(sin) * phi, & and &, plain(cos) * phi)), ylab = expression(&sin& * phi, &cos& * phi), xlab = expression(paste(&Phase Angle &, phi)), col.main = &blue&) #Hit &Return& to see next plot: sin and cos1.0 sin -1.0 -0.5 0.0 0.520 Phase Angle2 ? axis(1, at = c(-pi, -pi/2, 0, pi/2, pi), lab = expression(-pi,-pi/2, 0, pi/2, pi)) ? plot(1:10, type = &n&, xlab = &&, ylab = &&, main = &plot math & numbers&) ? tt &- 1.23 ? mtext(substitute(hat(theta) == that, list(that = tt))) ? for (i in 2:9) text(i, i + 1, substitute(list(xi, eta) == group(&(&, list(x, y), &)&), list(x = i, y = i + 1))) plot math & numbers^ 1.23109 10 8 987 8 6 765 6 4 543 4 2 32246810 ? plot(1:10, 1:10)#Hit &Return& to see next plot: ? text(4, 9, expression(hat(beta) == (X^t * X)^{-1} * X^t * y)) ? text(4, 8.4, &expression(hat(beta) == (X^t * X)^{-1} * X^t * y)&, cex = 0.8) ? text(4, 7, expression(bar(x) == sum(frac(x[i], n), i == 1, n))) ? text(4, 6.4, &expression(bar(x) == sum(frac(x[i], n), i==1, n))&, cex = 0.8) ? text(8, 5, expression(paste(frac(1, sigma * sqrt(2 * pi)), & &, plain(e)^{frac(-(x - mu)^2, 2 * sigma^2)})), cex = 1.2) 10^XX Xyt1 texpression(hat(beta) == (X^t * X)^{-1} * X^t * y)8nx6xii 1nexpression(bar(x) == sum(frac(x[i], n), i==1, n))1:101 24x2 2e2224 1:106810 其他Arithmetic Operators x+y x-y x*y x/y x %+-% y x%/%y x %*% y -x +x Sub/Superscripts x[i] x^2 Juxtaposition x*y paste(x, y, z) Lists list(x, y, z) xyz xy xyz plain(x) italic(x) bold(x) bolditalic(x) xi x2Radicals sqrt(x) sqrt(x, y) Relations x == y x != y x&y x &= y x&y x &= y x %~~% y x %=~% y x %==% y x %prop% y Typeface x x x x x y x y x y x y x y x y x y x y x y x yhat(x) tilde(x) ring(x) bar(xy)yEllipsisArrows x1 x1 x1 x1 xn xn xn xn x %&-&% y x %-&% y x %&-% y x %up% y x %down% y y y y y y y y x %&=&% y x %=&% y x %&=% y x %dblup% y x %dbldown% y x x x y y yx y x y xy x y x y x y x y x xx xlist(x[1], ..., x[n]) x[1] + ... + x[n] list(x[1], cdots, x[n]) x[1] + ldots + x[n]x y x y x x x y y ySet Relations x %subset% y x %subseteq% y x %supset% y x %supseteq% y x %notsubset% y x %in% y x %notin% y Accents ^ x ~ x ° x xy xy xy x x x x x x xx y x ySymbolic Names Alpha - Omega alpha - omega infinity 32 * degree 60 * minute 30 * second 32 60 30widehat(xy) widetilde(xy) Style displaystyle(x) textstyle(x) scriptstyle(x) scriptscriptstyle(x) Spacing x ~ ~y x y x xxxBig Operatorsnsum(x[i], i = 1, n)1xiprod(plain(P)(X == x), x)xPX xbintegral(f(x) * dx, a, b)af x dxnx + phantom(0) + yx 1yunion(A[i], i == 1, n)i 1 n i 1Ai Aix + over(1, phantom(0))xintersect(A[i], i == 1, n)Fractions x frac(x, y) y x over(x, y) y x atop(x, y) ylim(f(x), x %-&% 0)x 0lim f xmin(g(x), x &= 0)min g xx 0inf(S)infS sup Ssup(S)}

我要回帖

更多关于 长生劫第一章怎么过 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信