1
votes

In a folder I have an unfixed number of files (for example 4), each file contains 3 columns of data (day, temperature, pressure).

Example:

in the folder there are: 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
...  ...  ...      ... ... ...      ...  ...  ...      ...  ...   ...

I would like the R code to open all the files in the folder and save them in 3 separate files (Day, temperature, pressure)

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;

These files should be:

 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 
 ...   ...  ...  ...     ...  ...  ...  ...     ...   ...  ...  ...

Can you help me?

1
Why do you need to separate them into 3 files? Wouldn't it be better to read all files into 1 single data frame?Tung
To read all txt files, you can use the methods in this answerTung
This post might be of use, too: unix.stackexchange.com/questions/158408/…zx8754

1 Answers

0
votes

Read all the files, then loop through the list of dataframes and extract nth column:

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