SB123
SB123

Reputation: 1

print to file in a loop 'R'

I am a beginner to 'R'. I have a loop where I shift data frames, merge them and then run a regression:

testsequence = seq(60,120000, by=60)
for(n in 1:length(testsequence)){
 dfshift<-tail(df, (nrow(df)-testsequence[n]))
 df1shift<-head(df1, (nrow(df1)-testsequence[n]))
 dftogether<-cbind(dfshift,df1shift)
 lm1<-lm(LPGT~Temp, data=dftogether)
 write.table(lm1, file = "OUTPUT_Sensitivity_Results.csv")
}

The last line triggers this error message:

"Error in as.data.frame.default(x[[i]], optional = TRUE, stringsAsFactors = stringsAsFactors) : 
  cannot coerce class ""lm"" to a data.frame"

Any ideas? Also, I would like to structure it so that I don't overwrite my output file for each iteration of the loop. I saw the thread that suggested the following:

means <- sapply(filename, function(x) mean(as.numeric(read.table(x,header=FALSE)$V4)))

And then write the file as a whole with:

write.csv(data.frame(fname=filename,mean=means),file="output.csv")

but I'm not sure how to apply it to my case.

Any help would be appreciated!

Sonja

Upvotes: 0

Views: 743

Answers (1)

IRTFM
IRTFM

Reputation: 263332

If you want the lines that appear at the console as a result of the implicit Print in the REPL that runs at the top level of R, then use this instead:

 write( capture.output(print(lm1)),"\n",
        file="OUTPUT_Sensitivity_Results.txt",
        append=TRUE)

Note that I changed the file type so you would not think that it was a CSV file.

Upvotes: 2

Related Questions