r - 如何读取多个文本文件,为每个文件添加列标题,并在 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)出现在每个文本文件的第一行,但代码似乎不起作用。
我敢打赌,解决方案非常简单,但我还没有找到任何关于这个问题的有用信息......
解决方案
试试这个
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 = ",")
}
推荐阅读
- css - 位置:粘性;在路由器插座子组件中不起作用
- python - 为什么尽管放置了 subplot() 方法却没有显示情节?
- c# - 浮点数组到excel中的列(范围)
- git - 如何签出(下载)git存储库目录内的单个文件
- python - 如何使用烧瓶 python 以 JSON 格式发送原始数据。在 params 中发送数据时,它将数据作为表单数据(键值对)发送
- python - 水平图例表的动态宽度 - Plotly Express
- netsuite - 从 Netsuite 自定义 Excel 导出
- c++ - C++ WaveOut API 模糊测试声音
- sql - For count of records having more than 1 retrieve the least value
- javascript - 我需要进行按钮加载...在点击和加载之前的同时...检查所需的验证