读取文件并将列附加到txt文件

时间:2018-05-09 09:28:34

标签: r

在文件夹中,我有不确定数量的文件(例如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 
 ...   ...  ...  ...     ...  ...  ...  ...     ...   ...  ...  ...

你能帮助我吗?

1 个答案:

答案 0 :(得分:0)

阅读所有文件,然后遍历 dataframes 列表并提取 nth 列:

# 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)