Я предполагаю, что вы не просто хотите читать файлы, но на самом деле модифицируете файлы так, чтобы они содержали заголовки столбцов.
Чтобы следующий код работал, вам нужно определить две переменные: path
должен указывать на папку, в которой хранятся исходные файлы. out_path
должен быть путь к папке, где должны храниться измененные файлы. Если папка out_path
не существует, она будет создана.
Этот фрагмент кода читает все файлы csv в path
, добавляет заголовки и записывает измененные файлы в папку out_path
:
# create the output folder
# showWarnings = FALSE ensures that the function does not complain,
# even if the folder already exists
dir.create(out_path, showWarnings = FALSE)
# get the names of the input files with their full path
files <- list.files(path, "\\.csv", full.name = TRUE)
# loop through all the input files
for (file in files) {
# read the file, specify the correct separator
data <- read.table(file, sep = "|")
# set the column names
names(data) <- c("date", "level")
# define the output file name: the file should be written to
# out_path and have the same name as the original file
outfile <- file.path(out_path, basename(file))
# write the file. You need to specify the separator (|), and
# omit row names and quotes
write.table(data, outfile, sep = "|", row.names = FALSE, quote = FALSE)
}
Файл примера из вашего вопроса будет преобразован в:
date|level
09/21/1299 |23
09/22/1999 |25
09/23/1999 |25
Обратите внимание, что заголовки неправильно выровнены. Если файлы читаются как файлы CSV, это не должно быть проблемой.