r - 读取文件并将列附加到 txt 文件
问题描述
在一个文件夹中,我有不固定数量的文件(例如 4 个),每个文件包含 3 列数据(天、温度、压力)。
例子:
文件夹中有:file1.txt、file2.txt、file3.txt、file4.txt
file1.txt file2.txt. file3.txt. file4.txt
D1_1 T1_1 P1_1 D2_1 T2_1 P2_1 D3_1 T3_1 P3_1 D4_1 T4_1 P4_1
D1_2 T1_2 P1_2 D2_2 T2_2 P2_2 D3_2 T3_2 P3_2 D4_2 T4_2 P4_2
... ... ... ... ... ... ... ... ... ... ... ...
我希望 R 代码打开文件夹中的所有文件并将它们保存在 3 个单独的文件中(天、温度、压力)
legend Xn1_n2:
X=(D =day,T=temperature, P=pressure);
n1=(1,2,3,4 number of the file);
n2=number of measurements in the file;
这些文件应该是:
Day. temperature. pressure
D1_1 D2_1 D3_1 D4_1 T1_1 T2_1 T3_1 T4_1 T1_1 T2_1 T3_1 T4_1
D1_2 D2_2 D3_2 D4_2 T1_2 T2_2 T3_2 T4_2 T1_2 T2_2 T3_2 T4_2
... ... ... ... ... ... ... ... ... ... ... ...
你能帮助我吗?
解决方案
读取所有文件,然后遍历数据框列表并提取第 n列:
# read all the files
myFiles <- lapply(list.files(pattern = "^f.*.txt"), read.table, stringsAsFactors = FALSE)
# loop through list, and extract nth column, e.g.: Day, 1st column
myDay <- sapply(myFiles, "[[", 1)
myDay
# [,1] [,2] [,3] [,4]
# [1,] "D1_1" "D2_1" "D3_1" "D4_1"
# [2,] "D1_2" "D2_2" "D3_2" "D4_2"
# output to a file
write.table(myDay, "myDay.txt", row.names = FALSE, col.names = FALSE, quote = FALSE)
推荐阅读
- javascript - 节点js XMLHttpRequest问题
- pdf - 使用 Apache PDFBox 解析 PDF 文件以获取大纲
- python - 类的函数,调用时什么都不做
- python - 在python中导入模块时出错
- javascript - 在 javascript 中使用正则表达式无法获得正确的输出
- c - pthread_create 分段错误与 pthread_create.c 552
- hugo - 将原始html帖子添加到雨果不显示
- java - 如何确保数组包含某些值?
- c# - Visual C#,Codesoft 中的条码大小不变吗?
- c# - 为什么 Glav Web Cache 在从其他实例调用时没有我保存的数据?