1. 注意在pdf中绘图,每次plot都要调用dev.off()关闭设备
for(i in 1:10)
{
pdf(paste(i,'plots.pdf',sep=''))
plot(0)
dev.off()
}
上述代码中,如果dev.off移到循环外面,则只有最后的图能正常生成出来。
2. read.table函数跳过空白行
read.table的skip参数可以设置跳过前面的n行,blank.lines.skip参数可以设置跳过完全空白的行。
3. 对boxplot横坐标重新排序
InsectSprays1=data.frame(count=InsectSprays[,1],spray=ordered(InsectSprays[,2],levels=c("C","E","D","A","F","B")))
boxplot(count ~ spray, data =InsectSprays1, col = "lightgray")
4. 趣味实现:绘制时钟
A=seq(0,2*pi,length.out=1000)
x1=8*cos(A)
y1=8*sin(A)
x2=7*cos(A)
y2=7*sin(A)
plot(x1,y1,col="blue",lwd="0.01",xlim=c(-10,10),ylim=c(-10,10),asp=1)
points(x2,y2,col="blue",lwd="0.05")
for (k in 1:12)
{
xk=9*cos(-2*pi/12*k+pi/2)
yk=9*sin(-2*pi/12*k+pi/2)
lines(c(xk/9*8,xk/9*7),c(yk/9*8,yk/9*7),col="green")
text(xk,yk,k,col="red",lwd=0.1)
}
hour=as.integer(format(Sys.time(),"%H"))
min=as.integer(format(Sys.time(),"%M"))
sec=as.integer(format(Sys.time(),"%S"))
#计算时针的位置
th=-(hour+min/60+sec/3600)/12*2*pi+pi/2;
xh3=4.0*cos(th);
yh3=4.0*sin(th);
xh2=xh3/2+0.5*cos(th-pi/2);
yh2=yh3/2+0.5*sin(th-pi/2);
xh4=xh3/2-0.5*cos(th-pi/2);
yh4=yh3/2-0.5*sin(th-pi/2);
hh=polygon(c(0,xh2,xh3,xh4,0),c(0,yh2,yh3,yh4,0),col="red")
#hh=lines(c(0,xh2,xh3,xh4,0),c(0,yh2,yh3,yh4,0),col="red")
#计算分针的位置
tm=-(min+sec/60)/60*2*pi+pi/2;
xm3=6.0*cos(tm);
ym3=6.0*sin(tm);
xm2=xm3/2+0.5*cos(tm-pi/2);
ym2=ym3/2+0.5*sin(tm-pi/2);
xm4=xm3/2-0.5*cos(tm-pi/2);
ym4=ym3/2-0.5*sin(tm-pi/2);
hm=polygon(c(0,xm2,xm3,xm4,0),c(0,ym2,ym3,ym4,0),col="green")
#hm=lines(c(0,xm2,xm3,xm4,0),c(0,ym2,ym3,ym4,0),col="green")
#计算秒针的位置
ts=-sec/60*2*pi+pi/2;
hs=lines(c(0,6.5*cos(ts)),c(0,6.5*sin(ts)),col="black")
while(1)
{
hh=lines(c(0,xh2,xh3,xh4,0),c(0,yh2,yh3,yh4,0),col="white")
hm=lines(c(0,xm2,xm3,xm4,0),c(0,ym2,ym3,ym4,0),col="white")
hs=lines(c(0,6.5*cos(ts)),c(0,6.5*sin(ts)),col="white")
hour=as.integer(format(Sys.time(),"%H"))
min=as.integer(format(Sys.time(),"%M"))
sec=as.integer(format(Sys.time(),"%S"))
#计算时针的位置
th=-(hour+min/60+sec/3600)/12*2*pi+pi/2;
xh3=4.0*cos(th);
yh3=4.0*sin(th);
xh2=xh3/2+0.5*cos(th-pi/2);
yh2=yh3/2+0.5*sin(th-pi/2);
xh4=xh3/2-0.5*cos(th-pi/2);
yh4=yh3/2-0.5*sin(th-pi/2);
hh=polygon(c(0,xh2,xh3,xh4,0),c(0,yh2,yh3,yh4,0),col="red")
#hh=lines(c(0,xh2,xh3,xh4,0),c(0,yh2,yh3,yh4,0),col="red")
#计算分针的位置
tm=-(min+sec/60)/60*2*pi+pi/2;
xm3=6.0*cos(tm);
ym3=6.0*sin(tm);
xm2=xm3/2+0.5*cos(tm-pi/2);
ym2=ym3/2+0.5*sin(tm-pi/2);
xm4=xm3/2-0.5*cos(tm-pi/2);
ym4=ym3/2-0.5*sin(tm-pi/2);
hm=polygon(c(0,xm2,xm3,xm4,0),c(0,ym2,ym3,ym4,0),col="green")
#hm=lines(c(0,xm2,xm3,xm4,0),c(0,ym2,ym3,ym4,0),col="green")
#计算秒针的位置
ts=-sec/60*2*pi+pi/2;
hs=lines(c(0,6.5*cos(ts)),c(0,6.5*sin(ts)),col="black")
Sys.sleep(0.1)
}
5. 使用seq.Date函数生成日期序列
> date.range<-seq.Date(from =as.Date('2000-1-1'),to = as.Date('2001-1-1'),by = 'month')
> date.range
[1]"2000-01-01" "2000-02-01" "2000-03-01""2000-04-01" "2000-05-01" "2000-06-01""2000-07-01" "2000-08-01"
[9]"2000-09-01" "2000-10-01" "2000-11-01""2000-12-01" "2001-01-01"
6. 打开文件,建立连接,并按行读取文件
把下面的文件名换成你自己的文本文件,即可按行读取。
con <-file('C:/mtcars.csv',open='rt',encoding = 'latin1')#以只读方式建立连接
text <- readLines(con)
close(con) #注意关闭文件连接
7. 绘制三维圆锥图
library(lattice)
A<-matrix(ncol=2, nrow=64)
for(i in 0:63) { A[i+1,1]<-sin(i/10)
A[i+1,2]<-cos(i/10) }
Sigma<-matrix(c(0.5,0.1,0.1,0.25),byrow=TRUE,nrow=2)
G<-eigen(Sigma)
E1<-t(G$vector%*%t(A))
E2<-t(diag(sqrt(G$values))%*%t(E1))
mu<-c(0.1,0.2)
E3<-sweep(E2,2,-mu)
a<-sqrt(max(rowSums(sweep(E3,2,mu)**2)))
b<-sqrt(min(rowSums(sweep(E3,2,mu)**2)))
astar<-as.numeric(a+abs(mu[1]))
bstar<-as.numeric(b+abs(mu[2]))
xstar<-seq(-astar,astar,len=50)
ystar<-seq(-bstar,bstar,len=50)
g<-expand.grid(x=xstar,y=ystar)
p1<-2*g$x*mu[1]/a**2+2*g$y*mu[2]/b**2
p2<-(g$x**2/a**2+g$y**2/b**2)
p3<-mu[1]**2/a**2+mu[2]**2/b**2-1
q<-(p1+sqrt(p1**2-4*p2*p3))/(2*p2)
z<-sqrt(1-(q*g$x)**2-(q*g$y)**2)
zstar<-(z/q)
ind0<-!(q<1)
g$z<-zstar
sc<-matrix(c(rep(c(-1,-1,-1),sum(ind0))),nrow=sum(ind0),byrow=TRUE)
gstar<-rbind(g[ind0,],sc*g[ind0,])
group<-c(rep(1,nrow(gstar)/2),rep(2,nrow(gstar)/2))
gstar$group<-group
gstar <- g
gstar$z[!ind0] <- NA
gstar$z2 <- -gstar$z
wireframe(z + z2 ~ x * y, gstar,colorkey=TRUE,drape=TRUE, scales=list(arrows=FALSE))
8. 实现类似.NET LINQ功能的二元操作符
`%then%` = function(x, body) {
x= substitute(x)
fl = as.list(substitute(body))
car = fl[[1L]]
cdr = {
if (length(fl) == 1)
list()
else
fl[-1L]
}
combined = as.call(
c(list(car, x), cdr)
)
eval(combined, parent.frame())
}
df = data.frame(x = 1:7)
df %then% subset(x > 2) %then% print
This prints
x
3 3
4 4
5 5
6 6
7 7
(data.frame(
x= c(1, 1, 1, 2, 2, 2),
y= runif(6)
)
%then% subset(y > 0.2)
%then% ddply(.(x), summarize,
ysum = sum(y),
ycount = length(y)
)
%then% print
)
9. 提取table函数中的频数
freq <- table(c('a','b','c','b','c','a','d'))
Mat <- as.matrix(freq)
Mat[1:nrow(Mat)]
10. 创建使用ComboBox控件的界面
需要安装gWidgets2,gWidgets2RGtk2包
library(gWidgets2)
data(mtcars)
testdf <- data.frame(a=1:3, b= 1:3)
## list data frame names in envir
dfnms <- names(Filter(is.data.frame,mget(ls())) )
lsNms <- function(d,envir=.GlobalEnv) names(get(d,envir=envir))
w <- gwindow("two combos")
g <- glayout(cont=w)
g[1,1] <- "Data frames:"
g[1,2] <- (dfs <- gcombobox(dfnms,cont=g))
g[2,1] <- "Variables:"
g[2,2] <- (vnames <- gcombobox(character(0),cont=g))
addHandlerChanged(dfs,handler=function(...) vnames[] <-lsNms(svalue(dfs)))
11. ComboBox用户界面示例
library(gWidgets)
library(gWidgetsRGtk2)
options(guiToolkit="RGtk2")
w <- gwindow()
g <- ggroup(cont=w)
do_expand=TRUE
options <- glayout(cont=g, spacing=5,expand=do_expand)
items <- ""
options[1,1] = "vanilla"
options[1,2] <- gcombobox(items,cont=options)
options[2,1] = "expand"
options[2,2, expand=TRUE] <-gcombobox(items, cont=options)
options[3,1] = "expand, fill"
options[3,2, expand=TRUE,fill="y"] <- gcombobox(items, cont=options)
options[4,1] = "size"
options[4,2] <- (cb <-gcombobox(items, cont=options))
size(cb) <- c(250, -1)
## populate comboboxes
items <- state.name
sapply(options[,2], function(i) i[] <-items)
12. tcltk2包的ComboBox示例
library(tcltk2)
root<-tktoplevel()
v <- tclVar()
d <- tk2combobox(root, textvariable=v)
tkpack(d)
# works
tkconfigure(d, values=c("a string withspaces", "a second string"))
# inserts four items instead of one
spaceystr <- tclVar("a string withspaces")
tkconfigure(d, textvariable = spaceystr)
13.选择文件并将文件列入ComboBox的界面示例
library(gWidgets)
w <- gwindow("Testing",visible=FALSE)
g <- ggroup(cont=w, horizontal=FALSE)
fb <- gfilebrowse("Choose a CSVfile", quote=FALSE,
filter = list("CSVfiles"=list(patterns="*.csv")),
cont=g)
cb <- gcombobox("", cont=g)
addHandlerChanged(fb,handler=function(h,...) {
x<- read.csv(svalue(fb))
cb[] <- colnames(x)
})
visible(w) <- TRUE
14. 获取文件属性:大小、创建时间、修改时间等等
file.info("C:/Trace.txt")
size isdir mode mtime ctime atime exe
C:/Trace.txt 3 FALSE 666 2014-11-10 11:00:49 2013-12-24 17:51:18 2013-12-24 17:51:18 no
15. &和&&,|和||的区别
&和&&是“逻辑与”运算符,|和||是“逻辑或”运算符
对于两个向量来说,&和|会依次对两个向量中对应的数值进行逻辑运算,返回一个布尔值向量;而&&和||仅对第一个元素进行逻辑运算,仅返回一个布尔值。
> aa <-c(1,2,3,4,5,6)
> bb <-c(0,1,0,2,3,4)
> aa & bb
[1] FALSE TRUE FALSE TRUE TRUE TRUE
> aa &&bb
[1] FALSE
> aa | bb
[1] TRUE TRUE TRUETRUE TRUE TRUE
> aa || bb
[1] TRUE