0

也许有人可以帮助我。我在 R 中计算了不同的结果,现在我试图将它们合并到一个 txt 中。数据。但是,不知何故,我无法创建一个可以概览所有内容的数据文件。

一个名为“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

任何人都可以帮忙。

4

2 回答 2

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)

但是第二种方法不如第一种方法有效,因为每次您想向其中添加内容时都会打开和关闭文件。

于 2012-11-29T18:03:14.423 回答
0

data.frames 可以是列表的元素。

FinalTextFile <- list()
FinalTextFile$DataFrame <- DF
FinalTextFile$AverageTemperature <- mean(DF$Temperature)
FinalTextFile$MaximumTemperature <- max(DF$Temperature)
于 2012-11-29T17:48:54.873 回答