经常会遇到下载的基因表达数据,是分散在多个数据文件中,而我们为了得到基因表达矩阵,则必须要做的一步就是通过R语言合并这些表达文件。所以这里我们做一下几种不同的方法的对比:
例如这样的多个数据文件:

而单个文件的形式如下所示:

(1)通过sapply函数
setwd('D:\\SCIwork\\F14\\mRNA\\E-MEXP-1270\\E-GEOD-59363.processed.1')
files = list.files()
read_in <-function(x){
temp = read.table(x,header = T)
temp = temp[,-1]
return(temp)
}
system.time(data <- sapply(files,read_in))
dim(data)
(2)通过R循环加merge函数
time1 = Sys.time()
for(i in 1:length(files)){
if(i == 1) {
temp = read.table(files[i],header = T)
name <- substr(files[i], start = 1, stop = 12)
names(temp)[2] <- name
} else {
dt <- read.table(files[i],header = T)
name <- substr(files[i], start = 1, stop = 12)
names(dt)[2] <- name
temp = merge(temp, dt, by='ID_REF') }}
time2 = Sys.time()
time2 - time1
(3)通过R循环加cbind函数
time_1 = Sys.time()
input_mat = 1
for(i in 1:length(files)){
temp = read.csv(files[i],header = T)
temp = temp[,-1]
input_mat = cbind(input_mat,temp)
}
input_mat = input_mat[,-1]
time_2 = Sys.time()
time = time_1 - time_2
print(time)
通过上述的步骤,我们得到如下的表达矩阵。

(4)总结。
我们发现sapply函数读取的速度最快,循环加merge函数读取的速度最慢,但是循环加merge函数更容易理解,且更适合单个数据文件出现行名不相同时。
网友评论