写入文件可以使用write系列函数。
write.table(x, file = "", append = FALSE, quote = TRUE, sep = " ",
eol = "\n", na = "NA", dec = ".", row.names = TRUE,
col.names = TRUE, qmethod = c("escape", "double"),
fileEncoding = "")
write.csv(...)
write.csv2(...)
x |
要写入的对象, 最好是矩阵或者数据框. 如果不是,那就改成一个数据框 |
file |
输出文件名或路径 |
append |
逻辑值. 如果为真,则输出附加到文件中。如果为FALSE,则清空源文件 |
quote |
逻辑值 ( |
sep |
分隔符 |
eol |
the character(s) to print at the end of each line (row). For example, |
na |
将缺失值替换成 |
dec |
用于数字列或复杂列中的小数点的字符串:必须是单个字符。 |
row.names |
要么是一个逻辑值,指示是否要将x的行名与x一起写入,要么是一个要写入行名的字符向量。 |
col.names |
要么是一个逻辑值,指示是否要将x的列名与x一起写入,要么是一个要写入列名的字符向量。有关col.names = NA的含义,请参阅“CSV文件”一节。 |
qmethod |
a character string specifying how to deal with embedded double quote characters when quoting strings. Must be one of |
fileEncoding |
character string: if non-empty declares the encoding to be used on a file (not a connection) so the character data can be re-encoded as they are written. See |
... |
arguments to |
> class(rivers)
[1] "numeric"
> cat(rivers)
735 320 325 392 524 450 1459 135 465 600 330 336 280 315 870 906 202 329 290 1000 600 505 1450 840 1243 890 350 407 286 280 525 720 390 250 327 230 265 850 210 630 260 230 360 730 600 306 390 420 291 710 340 217 281 352 259 250 470 680 570 350 300 560 900 625 332 2348 1171 3710 2315 2533 780 280 410 460 260 255 431 350 760 618 338 981 1306 500 696 605 250 411 1054 735 233 435 490 310 460 383 375 1270 545 445 1885 380 300 380 377 425 276 210 800 420 350 360 538 1100 1205 314 237 610 360 540 1038 424 310 300 444 301 268 620 215 652 900 525 246 360 529 500 720 270 430 671 1770
> write.table(rivers,file='rivers.txt')
我们读入一个文件后,将其写入一个新的CSV文件中去。
write.table(CO2,file='co2.csv',sep=',')
但是这样,系统就会自动给文件加上行号和自定义列名,而再度读取时,会有两排行号
> read.table('co2.csv',sep=',',nrows = 10)
V1 V2 V3 V4 V5 V6
1 NA Plant Type Treatment conc uptake
2 1 Qn1 Quebec nonchilled 95 16
3 2 Qn1 Quebec nonchilled 175 30.4
4 3 Qn1 Quebec nonchilled 250 34.8
5 4 Qn1 Quebec nonchilled 350 37.2
6 5 Qn1 Quebec nonchilled 500 35.3
7 6 Qn1 Quebec nonchilled 675 39.2
8 7 Qn1 Quebec nonchilled 1000 39.7
9 8 Qn2 Quebec nonchilled 95 13.6
10 9 Qn2 Quebec nonchilled 175 27.3
有几分麻烦,因此可以添加参数。
> write.table(CO2,file='co2_2.csv',sep=',',row.names=FALSE)
> read.table('co2_1.csv',sep=',',nrows = 10,header = TRUE)
Qn1 Quebec nonchilled X95 X16
1 Qn1 Quebec nonchilled 175 30.4
2 Qn1 Quebec nonchilled 250 34.8
3 Qn1 Quebec nonchilled 350 37.2
4 Qn1 Quebec nonchilled 500 35.3
5 Qn1 Quebec nonchilled 675 39.2
6 Qn1 Quebec nonchilled 1000 39.7
7 Qn2 Quebec nonchilled 95 13.6
8 Qn2 Quebec nonchilled 175 27.3
9 Qn2 Quebec nonchilled 250 37.1
10 Qn2 Quebec nonchilled 350 41.8
酱紫就好了。