我想从许多文件的前3列中读取,我不一定知道每个文件包含的列数。另外,我并不完全知道每个文件中要跳过的行数,但在标题行之前不会超过19行。
我的问题类似于这些问题:
但我有不同的问题,即不知道我要导入的文件中的列数或要跳过的确切行数。我只想从每个文件中导入前三列,这些列始终命名为(Date/Time
,Unit
,Value
)。
关联问题的read.table
解决方案需要知道文件中的列数并为每列指定colClasses
。我试图通过lapply
的方法读取数千个文件,其中输入是.csv文件的列表,并在每个文件上使用read.table
:
lapply(files, read.table, skip=19, header=T, sep=",")
# 2ndary issue: # of lines to skip varies. maybe up to 19.
有没有办法解决提前不知道列数的问题?
编辑:我已经修改了@asb提供的答案以适应我的问题而且效果很好。my.read.table <- function (file, sep=",", colClasses3=c("factor","factor","numeric"), ...) {
## extract the first line of interest, the line where "Date/Time,Unit,Value" appears
first.line <- readLines(file, n=20)[grepl("Date/Time,Unit,Value",
readLines(file, n = 20)) == T]
## deteremine number of lines to skip (max possible = 19)
skip.number <- grep("Date/Time,Unit,Value",
readLines(file, n=20), value=FALSE)-1
## Split the first line on the separator to find # of columns
ncols <- length(strsplit(first.line, sep, fixed=TRUE)[[1]])
## fixed=TRUE to avoid needing to escape the separator.
# use ncols here in the `colClasses` argument
out <- read.table(file, sep=sep, header=TRUE, skip = skip.number,
colClasses=c(colClasses3, rep("NULL", ncols - 3)), ...)
out
}
答案 0 :(得分:1)
如果您知道分隔符,很容易知道有多少列。您可以为每个文件使用此类构造:
my.read.table <- function (file, sep=",", colClasses3=rep('double', 3), ...) {
first.line <- readLines(file, n=1)
## Split the first line on the separator.
ncols <- length(strsplit(first.line, sep, fixed=TRUE)[[1]])
## fixed=TRUE is to avoid the need to escape the separator when splitting.
out <- read.table(file, sep=sep,
colClasses=c(colClasses3, rep("NULL", ncols - 3)), ...)
out
}
然后使用您的解决方案:
lapply(files, my.read.table, skip=19, header=TRUE)
另外,请注意,您必须担心文件中是否包含rownames和colnames,因为当存在rownames和colnames时,read.table会应用某些智能。假设没有,则编写上述解决方案。请阅读colClasses
中的?read.table
,以进一步调整以满足您的需求。