1.基礎(chǔ)數(shù)據(jù)結(jié)構(gòu)
1.1 向量
# 創(chuàng)建向量a <-c(1, 2, 3, 4, 5, 6)
b<-c("one", "two", "three")
c<-c(TRUE, FALSE, TRUE, TRUE, FALSE)#向量索引a[2] #第二個(gè)元素a[-2] #刪除第二個(gè)元素a[c(2:4)] #取出第二到第四個(gè)元素[1] 2[1] 2[1] 1 3 4 5 6
圖片
1.2 矩陣
#創(chuàng)建矩陣mymat <- matrix(c(1:10), nrow=2, ncol=5, byrow=TRUE)#矩陣索引mymat[2,] #取第二行mymat[,2] #取第二列mymat[1,5] #第一行第五列的元素
圖片
1.3 數(shù)組
#創(chuàng)建數(shù)組myarr <- array(c(1:12),dim=c(2,3,2))
dim(myarr) #取矩陣或數(shù)組的維度myarr[1,2,1] #取第一個(gè)矩陣的第一行第二列
1.4 數(shù)據(jù)框
圖片
圖片
# 創(chuàng)建數(shù)據(jù)框kids <- c("Wang", "Li")
age <- c("18", "16")
df <- data.frame(kids, age)#數(shù)據(jù)框索引df[1,] #第一行df[,2] #第二列df[1:2,1:2]#前兩行噪馏,前兩列df$kids #根據(jù)列名稱(chēng)#數(shù)據(jù)框常用函數(shù)str(df) #數(shù)據(jù)框的結(jié)構(gòu)rownames(df) #行名稱(chēng)colnames(df) #列名稱(chēng)
1.4.1 因子變量
變量:類(lèi)別變量聊训,數(shù)值變量
類(lèi)別數(shù)據(jù)對(duì)于分組數(shù)據(jù)研究非常有用。(男女注益,高中低)
R中的因子變量類(lèi)似于類(lèi)別數(shù)據(jù)舶沿。
#向量因子化status<-c("Poor", "Improved", "Excellent", "Poor")
status<-factor(status,ordered=TRUE,
? ? levels= c("Poor","Improved", "Excellent"),
? ? labels=c("P","I","E"))
index <- sample(1:100,75)
plotdata <- data.frame(index,status)
attach(plotdata)
boxplot(index~status,col="red")
圖片類(lèi)別變量墙杯,有序變量稱(chēng)為因子,決定了數(shù)據(jù)的分析方式和視覺(jué)呈現(xiàn)形式
Attach()可以將數(shù)據(jù)框添加到R的搜索路徑中暑椰,當(dāng)R遇到一個(gè)變量名后霍转,將檢測(cè)搜索路徑中的數(shù)據(jù)框,定位這個(gè)變量
1.5 列表
列表以一種簡(jiǎn)單的方式組織和調(diào)用不相干的信息一汽,R函數(shù)的許多運(yùn)行結(jié)果都是以列表的形式返回
#創(chuàng)建列表lis <- list(name='fred',
? ? wife='mary',
? ? no.children=3,
? ? child.ages=c(4,7,9))#列表索引lis$name #列表組件名lis[[1]] #列表位置訪問(wèn)
常用函數(shù)
圖片
圖片
R流程控制
圖片
p <- 0.1
if(p<=0.05){? print("p<=0.05!")
}else{? print("p>0.05!")
}
圖片
for(i in 1:10) {? print(i)
}
i <- 1while(i<10)
? {? ? print(i)
? ? i <- i + 1
? }
圖片
v <- LETTERS[1:6]for (i in v){? if(i == 'D'){
? ? next
? }? print(i)
}
圖片
v <- LETTERS[1:6]for (i in v){? if(i == 'D'){? ? break
? }? print(i)
}
2.5 R函數(shù)
函數(shù)是組織好的避消,可重復(fù)使用的,用來(lái)實(shí)現(xiàn)單一召夹,或相關(guān)聯(lián)功能的代碼段
rcal<-function(x,y){
? z <- x^2 + y^2;
? result<-sqrt(z) ;
? result;
}
rcal(3,4)# 調(diào)用函數(shù)
3. 讀寫(xiě)數(shù)據(jù)
#數(shù)據(jù)讀入
getwd()
setwd('C:/Users/Administrator/Desktop/file')
dir()
top<-read.table("otu_table.p10.relative.tran.xls",header=T,row.names=1,sep='\t',stringsAsFactors = F)
top10<-t(top)
head(top10, n=2)#數(shù)據(jù)寫(xiě)出logtop10<-log(top10+0.000001)
write.csv(logtop10,file="logtop10.csv", quote=FALSE,? row.names = TRUE)
write.table(logtop10,file="logtop10.xls",sep="\t", quote=FALSE,
? ? row.names = TRUE, col.names = TRUE)
其他常用函數(shù)
圖片
4.數(shù)據(jù)清理
圖片
4.1 tidyr包
tidyr包的四個(gè)函數(shù)
寬數(shù)據(jù)轉(zhuǎn)為長(zhǎng)數(shù)據(jù):gather()
長(zhǎng)數(shù)據(jù)轉(zhuǎn)為寬數(shù)據(jù):spread()
多列合并為一列: unite()
將一列分離為多列:separate()
library(tidyr)
gene_exp <- read.table('geneExp.csv',header = T,sep=',',stringsAsFactors = F)
head(gene_exp) #gather 寬數(shù)據(jù)轉(zhuǎn)為長(zhǎng)數(shù)據(jù)gene_exp_tidy <- gather(data = gene_exp, key = "sample_name", value = "expression", -GeneID)
head(gene_exp_tidy)#spread 長(zhǎng)數(shù)據(jù)轉(zhuǎn)為寬數(shù)據(jù)gene_exp_tidy2<-spread(data = gene_exp_tidy, key = "sample_name", value = "expression")
head(gene_exp_tidy2)
圖片
4.2 dplyr包
dplyr包五個(gè)函數(shù)用法:
篩選: filter
排列: arrange()
選擇: select()
變形: mutate()
匯總: summarise()
分組: group_by()
library(tidyr)
library(dplyr)
gene_exp <- read.table("geneExp.csv",header=T,sep=",",stringsAsFactors = F)
gene_exp_tidy <- gather(data = gene_exp, key = "sample_name", value = "expression", -GeneID)#arrange 數(shù)據(jù)排列g(shù)ene_exp_GeneID <- arrange(gene_exp_tidy, GeneID)#降序加deschead(gene_exp_GeneID )#filter 數(shù)據(jù)按條件篩選gene_exp_fiter <- filter(gene_exp_GeneID ,expression>10)
head(gene_exp_fiter)#select 選擇對(duì)應(yīng)的列g(shù)ene_exp_select <- select(gene_exp_fiter ,sample_name,expression)
head(gene_exp_select)
圖片
5. 繪圖
圖片
5.1 長(zhǎng)數(shù)據(jù)與寬數(shù)據(jù)
圖片
library(tidyr)
library(ggplot2)#基礎(chǔ)繪圖file <- read.table("geneExp.csv",header=T,sep=",",stringsAsFactors = F,row.names = 1)#寬數(shù)據(jù)file
barplot(as.matrix(file),names.arg = colnames(file), beside =T ,col=terrain.colors(6))
legend("topleft",legend = rownames(file),fill = terrain.colors(6))#ggplot2繪圖gene_exp <- read.table("geneExp.csv",header=T,sep=",",stringsAsFactors = F)
gene_exp_tidy <- gather(data = gene_exp, key = "sample_name", value = "expression", -GeneID)#長(zhǎng)數(shù)據(jù)head(gene_exp_tidy)
ggplot(gene_exp_tidy,aes(x=sample_name,y=expression,fill=GeneID)) + geom_bar(stat='identity',position='dodge')
圖片
5.2 圖形參數(shù)位置
圖片
x <- rnorm(20, 2, 1)
y <- rnorm(20, 4, 2)
plot(x, y, cex=c(1:3), type="p", pch=19, col = "blue",
? ? cex.axis=1.5, col.axis="darkgreen", font.axis=2,
? ? main="這是主標(biāo)題:plot初試", font.main=2, cex.main=2, col.main="green",
? ? sub="這是副標(biāo)題:圖1", font.sub=3, cex.sub=1.5, col.sub="red",
? ? xlab="這是x軸標(biāo)簽", ylab="這是y軸標(biāo)簽",cex.lab=1.5, font.lab=2, col.lab="grey20",
? ? xlim=c(0,3), ylim=c(0,7))
abline(h=2, v=3, lty=1:2, lwd=2,col="red")
legend("topright", legend="我是圖例\n我在這兒",
? ? ? text.col="red", text.width=0.5)#Rnorm正態(tài)分布 個(gè)數(shù) 平均值 標(biāo)準(zhǔn)差 plot是泛型函數(shù)岩喷,根據(jù)輸入類(lèi)型的不同而變化#Type p 代表點(diǎn) l 代表線 b 代表兩者疊加
圖片
圖形參數(shù):
符號(hào)和線條:pch、cex监憎、lty纱意、lwd
顏色:col、col.axis鲸阔、col.lab偷霉、col.main、col.sub褐筛、fg类少、bg
文本屬性:cex、cex.axis渔扎、cex.lab硫狞、cex.main、cex.sub晃痴、font残吩、font.axis、font.lab倘核、font.main泣侮、font.sub
文本添加、坐標(biāo)軸的自定義和圖例
title()紧唱、main旁瘫、sub祖凫、xlab琼蚯、ylab酬凳、text()
axis()、abline()
legend()
多圖繪制時(shí)候遭庶,可使用par()設(shè)置默認(rèn)的圖形參數(shù)
par(lwd=2, cex=1.5)
圖形參數(shù)設(shè)置:
par(optionname=value,…)
par(pin=c(width,height)) 圖形尺寸
par(mfrow=c(nr,nc)) 圖形組合宁仔,一頁(yè)多圖
layout(mat) 圖形組合,一頁(yè)多圖
par(mar=c(bottom,left,top,right)) 邊界尺寸
par(fig=c(x1,x2,y1,y2),new=TURE) 多圖疊加或排布成一幅圖
#圖形組合:attach(mtcars)
opar <- par(no.readonly=TRUE) #復(fù)制當(dāng)前圖形參數(shù)設(shè)置par(mfrow=c(2,2))#設(shè)置圖形參數(shù)#layout(matrix(c(1,2,2,3),2,2,byrow=TRUE))plot(wt,mpg,main="Scatterplot of wt vs mpg")
hist(wt,main="Histogram of wt")
boxplot(wt,main="Boxplot of wt")
par(opar) #返回原始圖形參數(shù)detach(mtcars)
圖片
5.3 柱形圖
file <- read.table("barData.csv",header=T,row.names=1,sep=",",stringsAsFactors = F)
dataxx <- as.matrix(file) #轉(zhuǎn)化為矩陣cols <- terrain.colors(3) #抽取顏色#誤差線函數(shù)plot.error <- function(x, y, sd, len = 1, col = "black") {
? len <- len * 0.05
? ? arrows(x0 = x, y0 = y, x1 = x, y1 = y - sd, col = col, angle = 90, length = len)
? ? arrows(x0 = x, y0 = y, x1 = x, y1 = y + sd, col = col, angle = 90, length = len)
}
x <- barplot(dataxx, offset = 0, ylim=c(0, max(dataxx) * 1.1),axis.lty = 1, names.arg = colnames(dataxx), col = cols, beside = TRUE)
box()
legend("topright", legend = rownames(dataxx), fill = cols, box.col = "transparent")
title(main = "An example of barplot", xlab = "Sample", ylab = "Value")
sd <- dataxx * 0.1 for (i in 1:3) {
? plot.error(x[i, ], dataxx[i, ], sd = sd[i, ])
}
圖片
5.4 二元圖
圖片
matdata <- read.table("plot_observed_species.xls", header=T)
tbl_df(matdata) #查看數(shù)據(jù)屬性和結(jié)構(gòu)y<-matdata[,2:145]
attach(matdata)
matplot(series,y,
? ? ? ? ylab="Observed Species Number",xlab="Sequences Number",
? ? ? ? lty=1,lwd=2,type="l",col=1:145,cex.lab=1.2,cex.axis=0.8)
legend("topleft",lty=1, lwd=2, legend=names(y)[1:8],
? ? ? cex=0.5,col=1:145)
detach(matdata)
圖片
5.5 餅狀圖
relative<-c(0.270617,0.177584,0.194911,0.054685,0.048903,0.033961, 0.031195,0.188143)
taxon<-c("Sordariales","Pleosporales","Agaricales","Hypocreales",? "Pezizales","Eurotiales","Helotiales","Others")
ratio<-round(relative*100,2)
ratio<-paste(ratio,"%",sep="")
label<-paste(taxon,ratio,sep=" ")
pie(relative,labels=label, main="ITS1-Sample S1",? radius=1,col=rainbow(length(label)),cex=1.3)
library(plotrix)
fan.plot(relative,labels=label,main="Fan plot")
pie3D(relative,labels=label, height=0.2, theta=pi/4, explode=0.1, col=rainbow(length(label)),? border="black",font=2,radius=1,labelcex=0.9)
圖片
5.6 直方圖
seqlength<-rnorm(1000, 350, 30)hist(seqlength,breaks=100,
? ? col="red",freq=FALSE,
? ? main="Histogram with dengsitycurve",? ? ylab="Density", xlab="Sequence length")lines(density(seqlength),col="blue4",lwd=2)
圖片
5.7 聚類(lèi)圖
clu <- read.table("unweighted_unifrac_dm.txt", header=T, row.names=1, sep="\t")
head(clu)
dis <- as.dist(clu)
h <- hclust(dis, method="average")
plot(h, hang = 0.1, axes = T, frame.plot = F, main="Cluster Dendrogram based on unweighted_unifrac", sub="UPGMA")
圖片
5.8 維恩圖
library(VennDiagram)
ven<-list(sample1=20:50,? sample2=c(1:30,50:80), sample3=40:90, sample4=c(10:30,70:100))
venn.diagram(ven, filename='venn.png', cex=1.2, col="black", alpha= 0.50,lwd =1.2, cat.cex=1.4,
? ? ? ? ? ? ? fill=c("cornflowerblue", "green", "Gold1","darkorchid1"),? margin=0.15)
圖片
圖片輸出
直接導(dǎo)出
圖片
命令
pdf(file="file.pdf", width=7, height=10)
png(file="file.png",width=480,height=480)
jpeg(file="file.png",width=480,height=480)
tiff(file="file.png",width=480,height=480)
dev.off()