首页 > 解决方案 > 读取文件并将列附加到 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 
 ...   ...  ...  ...     ...  ...  ...  ...     ...   ...  ...  ...

你能帮助我吗?

标签: r

解决方案


读取所有文件,然后遍历数据框列表提取第 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)

推荐阅读