传统的一个一个文件合并通常费时费力,还可能出错,此时批量合并这些文件就显得比较重要。下面简单介绍基于R的批量合并多个相同格式文件的方法。
程序如下:
- setwd("D:/R practice")
- ## 示例数据.
- patientID <- c(1, 2, 3, 4)
- name<- c("lts", "has", "grl", "lst")
- age <- c(25, 34, 28, 52)
- patientdata1 <- data.frame(patientID, name, age)
- write.table(patientdata1, file="patientdata1.txt", quote=F, sep = "\t", row.names = F)
- patientID <- c(5, 6, 7, 8)
- name<- c("gss", "txs", "mrx", "qst")
- age <- c(45, 38, 37, 15)
- patientdata2 <- data.frame(patientID, name, age)
- write.table(patientdata2, file="patientdata2.txt", quote=F, sep = "\t", row.names = F)
- con=dir()
- ## 分步合并所有数据演示.
- last=data.frame()
- text=read.table(con[1],header=T)
- last=rbind(last,text)
- text=read.table(con[2],header=T)
- last=rbind(last,text)
- ## 循环语句合并所有数据演示.
- last=data.frame()
- for(i in 1:length(con))
- {text=read.table(con[i],header=T)
- last=rbind(last,text)}
- ## 循环语句合并每个数据库的前两行演示.
- last=data.frame()
- for(i in 1:length(con))
- {text=read.table(con[i],header=T)
- text=text[1:2,]
- last=rbind(last,text)}
- ## 循环语句合并每个数据库的前两列演示.
- last=data.frame()
- for(i in 1:length(con))
- {text=read.table(con[i],header=T)
- text=text[,1:2]
- last=rbind(last,text)}
如果大家有更好、更简便的方法,或者更好的示例说明如何处理类似问题,欢迎跟帖,^_^