我正在使用read.fwf函数组合多个.txt文件。我的问题是,每个文本文件的前面都有几个标题行,在数据实际开始之前从23到28行不等。我想以某种方式删除文件中的前n行,以便导入和梳理的都是数据本身。
有没有人有任何关于如何做的线索?每个数据文件的开头都是相同的("01Jan"),后面跟着一年。我基本上想删除文件中01号之前的所有内容。
现在,我的代码看起来像这样:
for (i in 1:length(files.x)){
if (!exists("X")){
X<-read.fwf(files.x[i], c(11,5, 16), header=FALSE, skip=23, stringsAsFactors=FALSE)
X<-head(X, -1) #delete the last row of each table
names(X)<-c("Date", "Time", "Data")
} else if (exists("X")){
temp_X<-read.fwf(files.x[i], c(11,5,16), header=FALSE, skip=23, stringsAsFactors=FALSE) #read in fixed width file
temp_X<-head(temp_X, -1)
names(temp_X)<-c("Date", "Time", "Data")
X<-rbind(X, temp_X) }}
我需要skip=23根据正在读入的文件而有所不同。除了手动读取每个文件然后合并之外,还有什么想法吗?
发布于 2014-06-14 02:56:54
也许吧
hdr <- readLines(files.x[i],n=50) ## or some reasonable upper bound
firstLine <- grep("^01Jan",hdr)[1]
X <- read.fwf(files.x[i], skip=firstLine-1, ...)此外,先通过fileList <- lapply(files.x,getFile) (其中getFile是您编写的一个小实用函数,用于将读取逻辑封装在单个文件中)再通过do.call(rbind,fileList)读取所有文件会更有效
https://stackoverflow.com/questions/24212139
复制相似问题