2012-11-29 21 views
0

中使用不同的行和列創建一組數據,也許有人可以幫助我。我在R中計算了不同的結果,現在我正試圖在一個txt中合併這些結果。數據。但是,不知何故,我無法創建一個數據文件,我可以對所有內容進行概述。如何在R

一個數據幀被稱爲 「min.temp」 與13行和3列(ID,日期和值)

id Date  Temperature 

1. 1967-04-25 -3.086980 
2. 1969-04-20 -4.489397 
3. 1972-04-26 -5.587154 
4. 1976-04-29 -5.684246 
5. 1976-04-30 -5.297752 
6. 1977-04-20 -3.615099 
7. 1981-04-21 -3.672259 
8. 1981-04-24 -3.860317 
9. 1991-04-20 -4.021680 
10. 1991-04-21 -6.366689 
11. 1991-04-22 -4.785906 
12. 1997-04-21 -4.989829 
13. 1997-04-22 -4.447067 

和其他2個值 「aver.temp」 和 「max.temp」 只有1每行2列:

Average temperature: 10 

Maximum temperature: 25 

我試圖合併所有信息列表,但它在某種程度上破壞了我的列表,當我嘗試整合所有的人。我的目標是獲得一個名爲temperature.txt的txt.file,我可以在其中爲aver.temp和max.temp分開行,然後由其餘的行跟蹤。最後,它應該看起來像這樣。

Average temperature: 10 

Maximum temperature: 25 

id. Date  Temperature 

1. 1967-04-25 -3.086980 
2. 1969-04-20 -4.489397 
3. 1972-04-26 -5.587154 
4. 1976-04-29 -5.684246 
5. 1976-04-30 -5.297752 
6. 1977-04-20 -3.615099 
7. 1981-04-21 -3.672259 
8. 1981-04-24 -3.860317 
9. 1991-04-20 -4.021680 
10. 1991-04-21 -6.366689 
11. 1991-04-22 -4.785906 
12. 1997-04-21 -4.989829 
13. 1997-04-22 -4.447067 

任何人都可以幫忙。

+0

不是在這個問題中找到問號。 :( –

+0

'?cat',''write.table'。你會想要使用'append = TRUE'。另請參閱'?capture.output'和'?sink' – GSee

回答

0

data.frame s可以是列表的元素。

FinalTextFile <- list() 
FinalTextFile$DataFrame <- DF 
FinalTextFile$AverageTemperature <- mean(DF$Temperature) 
FinalTextFile$MaximumTemperature <- max(DF$Temperature) 
+3

肯定看起來不像文本文件... – GSee

+0

對,這是一個列表,我假設他可以弄清楚該怎麼辦 –

+0

對,然後,-1從我 – GSee

4

用於寫入文件(catwritewrite.table等),大多數功能也可以寫入到文件的連接,這是寫的東西多到一個文件中更好的方法。在你的情況下,它會是這個樣子:

fh <- file("output.txt", "w") # creates a file connection 

cat("Average temperature: 10", "\n", file = fh) 
cat("Maximum temperature: 25", "\n", file = fh) 
write.table(min.temp, file = fh) 

close(fh) # closes the file connection 

另一種方法是使用append選項大多數這些功能還提供:

cat("Average temperature: 10", "\n", file = "output.txt", append = TRUE) 
cat("Maximum temperature: 25", "\n", file = "output.txt", append = TRUE) 
write.table(min.temp, file = "output.txt", append = TRUE) 

但這第二種方法是不是有效率每當你想添加一些東西時,第一個作爲文件被打開和關閉。

+1

'sink()'? –

+1

'sink'用於重定向sc重新輸出到一個文件。由於R輸出主要來自用戶幾乎無法控制的'print'語句,因此我覺得'sink'可能更適合於會話日誌之類的內容,而我的解決方案適用於創建報告或以特定格式導出數據。 – flodel

+0

嘿社區。非常感謝。是否有捕獲輸出... – user1851405