|
最近在處理一批數(shù)據(jù)量較大的數(shù)據(jù),需要多次讀入+導(dǎo)出,并且還需要計算微生物α多樣性指標(biāo)。為了減少重復(fù)代碼及減輕工作量。嘗試定義函數(shù)和編寫循環(huán)解決當(dāng)前問題。這里主要涉及內(nèi)容:批量導(dǎo)入數(shù)據(jù)+定義計算α多樣性指標(biāo)的函數(shù)+批量導(dǎo)出。下面直接對代碼進(jìn)行講解~由于目前數(shù)據(jù)還未發(fā)表,這里重新定義了函數(shù)來生成隨機(jī)矩陣模擬OTU數(shù)據(jù)(這里非常感謝師兄的指點和幫助)。#加入以下R包是為了運(yùn)行read.xlsx這個函數(shù) library(xlsx) library(openxlsx) library(xlsxjars) library(rJava)
##### 定義函數(shù)隨機(jī)生成N個矩陣(n行,n列)###### #由于數(shù)據(jù)還未發(fā)表,這里定義函數(shù)生成隨機(jī)矩陣,來模擬otu數(shù)據(jù) set.seed(1) #只要涉及隨機(jī)數(shù)都需要設(shè)定種子 random_matrix <- function(n, nrow, ncol) { #主要的函數(shù)體 df = list() #生成一個空的df為list()結(jié)構(gòu) otu = paste0("otu_", 1:ncol) #設(shè)置OTU id sample = paste0("sample_", 1:nrow) #設(shè)置samples id for (i in 1:n) { #第一次循環(huán),是為了生成矩陣 df[[i]] = matrix(NA,nrow,ncol) #循環(huán)生成N個矩陣并裝進(jìn)df這個list()中 df[[i]] = data.frame(df[[i]]) #將list轉(zhuǎn)成數(shù)據(jù)框結(jié)構(gòu),以便添加行名和列名 colnames(df[[i]]) = otu #對df所有數(shù)據(jù)框賦值列名 rownames(df[[i]]) = sample #賦值行名 for (j in seq_along(df[[i]])) { #嵌套循環(huán) df[[i]][j] = sample(0:300,nrow,replace = T) #前面生成的矩陣是NA空值,這里循環(huán)生成N行、N列0~300的隨機(jī)數(shù) } #list()中 df[[]][] 前面的雙括號表示讀取到哪個矩陣,后面單括號表示讀取該矩陣的哪一列 } return(df) #返回給df }
#生成6個矩陣,每個矩陣10行,200列 data <- random_matrix(n=6, nrow= 10, ncol= 200) # n nrow ncol 可以根據(jù)自己的喜好,隨便設(shè)定 #直接以不同sheet的形式一次性導(dǎo)出至一個excel中 write.xlsx(data, "mydata.xlsx", append=T, row.names=T)
###### 批量導(dǎo)入同excel中的多個sheet ####### library(tidyverse) sheet.index <- c(1:6) #1至6個sheet 6可以才成n 這里根據(jù)自己的excel中的情況修改 re <- map(sheet.index, ~ read.xlsx("mydata.xlsx", sheet=. )) #一次性導(dǎo)入excel中1到6個sheet str(re) #可以查看到導(dǎo)入的數(shù)據(jù)集是list結(jié)構(gòu),其中包含6個data.frame,也就是6個sheet
###### 定義函數(shù)計算alpha多樣性 ######
alpha_diversity <- function(x){ library(vegan) #由于α多樣性有些指標(biāo)需要基于vegan包 這里加載R包 x = data.matrix(x) #轉(zhuǎn)換矩陣 shannon = diversity(x,index="shannon") #香濃指標(biāo) richness = specnumber(x) #豐富度 simpson = diversity(x, index = "simpson") #辛普森指數(shù) Chao1 = estimateR(x)[2,] #Chao1指數(shù) eveness = shannon / log(richness) #均勻度 a = data.frame(shannon, richness,simpson,Chao1,eveness) #用數(shù)據(jù)框打包計算的結(jié)果 return(a) }
#構(gòu)建一個list來裝對應(yīng)不同sheet中計算alpha多樣性的結(jié)果 b <- list() #循環(huán)計算sheet的過程 for(i in seq_along(re)){ b[[i]] <- alpha_diversity(re[[i]]) #循環(huán)計算re這個list()中每個數(shù)據(jù)框并裝到b列表中 } #查看結(jié)果 head(b)
###### 批量導(dǎo)出多個sheet到同一個excel ###### for(i in 1:6){ sample <- paste0("sample_", 1:nrow(re[[i]])) #這里生成對應(yīng)數(shù)據(jù)集中行行數(shù)的樣本名 rownames(b[[i]]) <- sample #并賦值給b數(shù)據(jù)集中每個data.frame作為行名 write.xlsx(b, file = "C:/Users/Zz/Desktop/a.xlsx", append=T, row.names=T) #輸出所有計算結(jié)果并導(dǎo)出至一個excel中 } 用R markdown輸出結(jié)果: 
 這里是循環(huán)得到虛擬的數(shù)據(jù)集。



這里是循環(huán)得到α多樣性的結(jié)果。
|