R 小技巧收集

在一个图上画多个平滑曲线:

d1 <- cbind(rnorm(100), rnorm(100,3,1))
d2 <- cbind(rnorm(100), rnorm(100,1,1))
plot(d1[,1], d1[,2], xlim=range(c(d1[,1], d2[,1])), ylim=range(c(d1[,2], d2[,2])), col="blue", xlab="X", ylab="Y")
points(d2[,1], d2[,2], col="red")
points(loess.smooth(d1[,1], d1[,2]), type="l", col="blue")
points(loess.smooth(d2[,1], d2[,2]), type="l", col="red")

随机取样,缩小绘图时的样本量

# take a random sample of size 50 from a dataset mydata
# sample without replacement
mysample <- mydata[sample(1:nrow(mydata), 50,
   replace=FALSE),]

在一个图上画多个丰度曲线(柱状图)

d1 <- cbind(rnorm(100), rnorm(100,3,1))
d2 <- cbind(rnorm(100), rnorm(100,1,1))
d3 <- cbind(rnorm(100), rnorm(100,5,1))
ds1<-density(d1)
ds2<-density(d2)
ds3<-density(d3)
xr<-range(c(ds1$x,ds2$x,ds3$x))
yr<-range(c(ds1$y,ds2$y,ds3$y))
plot(ds1,xlim=xr,ylim=yr,col='black')
lines(ds2,col='blue')
lines(ds3,col='red')

逐行比较两个矩阵

ar1 <- array(data=c(1:16),dim=c(4,4))
ar2 <- array(data=c(1,2,3,3,5:16),dim=c(4,4))
z<-ar1==ar2
ar1
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 4 8 12 16
ar2
[,1] [,2] [,3] [,4]
[1,] 1 5 9 13
[2,] 2 6 10 14
[3,] 3 7 11 15
[4,] 3 8 12 16
z
[,1] [,2] [,3] [,4]
[1,] TRUE TRUE TRUE TRUE
[2,] TRUE TRUE TRUE TRUE
[3,] TRUE TRUE TRUE TRUE
[4,] FALSE TRUE TRUE TRUE
which(z==FALSE)
[1] 4

Or

apply(ar1==ar2,1,all)

在同一行行首开始重新输出,适用于显示进度,比如说任务进行至第几行。

 > for (i in 1:10) {
 >    cat("Number",i,"\r")
 >    flush.console()
 >    Sys.sleep(1)
 > }
 > cat("\n")

发表评论

电子邮件地址不会被公开。 必填项已用*标注