各ファイルに含まれる列の数が必ずしもわからない多くのファイルから最初の 3 列を読み取りたい。さらに、各ファイルでスキップする行数が正確にはわかりませんが、ヘッダー行の前に 19 行を超えることはありません。
私の質問はこれらの質問に似ています:
しかし、インポートしたいファイルの列数やスキップする正確な行数がわからないという別の問題があります。すべてのファイルから最初の 3 つの列のみをインポートしたいのですが、これらの列には一貫して名前が付けられています ( 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
}