I have a folder with 20 text files from several instrument runs. The data section all have the same format like this
22/05/11; 16:03:28; 0.000; 6.079; 31.41; 84881; 25.60; E0;
22/05/11; 16:03:29; 0.017; 6.063; 31.44; 84868; 25.60; E0;
22/05/11; 16:03:30; 0.034; 6.079; 31.41; 84868; 25.60; E0;
22/05/11; 16:03:31; 0.051; 6.079; 31.41; 84868; 25.60; E0;
22/05/11; 16:03:32; 0.068; 6.068; 31.43; 84868; 25.60; E0;
22/05/11; 16:03:33; 0.085; 6.068; 31.43; 84881; 25.60; E0;
22/05/11; 16:03:34; 0.102; 6.079; 31.41; 84874; 25.60; E0;
What I would like to do is read in every file within my folder, run a linear regression, and pull out the slope and R2 value.
As of now, this is my code for doing this for a single file.
O2=read.table("Coral 1_Dark.txt",skip=58, sep=";",header=FALSE)
names(O2)<-c("Date","Time","Log_Time","O2_mgL","Phase","Amp","Temp C","Error Message")
O2$id<-seq_len(nrow(O2)) #creates unique ID for each measurement (use for regression)
attach(O2)
fit=lm(O2_mgL~id)
summary(fit)
After running this code, I have been manually entering the slope and R2 data.
For now I can create a variable that contains all the files I am interested in with
F=list.files()
Which gives me all 20 files
[1] "Coral 1_Dark.txt" "Coral 1_Light.txt" "Coral 10_Dark.txt" "Coral 10_Light.txt" "Coral 2_Dark.txt"
[6] "Coral 2_Light.txt" "Coral 3_Dark.txt" "Coral 3_Light.txt" "Coral 4_Dark.txt" "Coral 4_Light.txt"
[11] "Coral 5_Dark.txt" "Coral 5_Light.txt" "Coral 6_Dark.txt" "Coral 6_Light.txt" "Coral 7_Dark.txt"
[16] "Coral 7_Light.txt" "Coral 8_Dark.txt" "Coral 8_Light.txt" "Coral 9_Dark.txt" "Coral 9_Light.txt"
And what I would like to end up with would be something like this for all 20 files
Coral Slope R2
Coral 1_Dark 0.23 98.3
Coral 2_Dark 0.33 99.3
ect
Any suggestions? I’ve never worked with any of the apply functions or any kind of loop- but I’m thinking this is about to change…..
Something like this?