首页 > 解决方案 > 如何读取多个文本文件,为每个文件添加列标题,并在 R 中用新文件覆盖旧文件?

问题描述

我有多个 .txt 格式的 EEG 数据文件都保存在一个文件夹中,我希望 R 读取所述文件夹中的所有文件,添加列标题(即电极编号,由从 1 到 129 的有序数字表示)到每个文件,并用新文件覆盖旧文件。

rm(list=ls())

setwd("C:/path/to/directory")

files <- Sys.glob("*.txt")

for (file in files){

  # read data:
  df <- read.delim(file, header = TRUE, sep = ",")

  # add header to every file: 
  colnames(df) <- paste("electrode", 1:129, sep = "")

  # overwrite old text files with new text files:
  write.table(df, file, append = FALSE, quote = FALSE, sep = ",", row.names = FALSE, col.names = TRUE)

}

我希望有序数字的列标题(即,电极 1 到电极 129)出现在每个文本文件的第一行,但代码似乎不起作用。

我敢打赌,解决方案非常简单,但我还没有找到任何关于这个问题的有用信息......

标签: rdata-science

解决方案


试试这个

for (file in files) {
  df = read.delim(file,header = FALSE,sep = ",")
  colnames(df) = paste("electrode",1:129,sep = "")
  write.table(df, file = "my_data.txt", sep = ",")  
}

推荐阅读