R write.csv() Function - Writing CSV Files
The R write.csv() function is used to save a data frame as a CSV file.
The CSV format can be opened directly in tools like Excel and is the most commonly used format for data output.
The syntax of the write.csv() function is as follows:
write.csv(x, file, row.names = TRUE, fileEncoding = "")
Parameter Description:
-
x The data frame or matrix to write.
-
file The output file path.
-
row.names Whether to save row names, defaults to TRUE. It is recommended to set FALSE to avoid an extra column.
Example
Create the processed data
df
<-
data.frame
(
Product
=
c
(
"Product A"
,
"Product B"
,
"Product C"
)
,
Sales
=
c
(
120
,
85
,
150
)
,
Unit price
=
c
(
9.9
,
15.8
,
5.6
)
)
Write CSV (without row names)
write.csv
(
df
,
"temp_products.csv"
,
row.names
=
FALSE
)
Verify: read back and display
data
<-
read.csv
(
"temp_products.csv"
)
(
"Saved and read-back data:"
)
(
data
)
View the raw written content
lines
<-
readLines
(
"temp_products.csv"
)
(
"CSV content:"
)
(
lines
)
The output of the code above is:
[1] "保存并读回的数据:"
产品 销量 单价
1 产品A 120 9.9
2 产品B 85 15.8
3 产品C 150 5.6
[1] "CSV 内容:"
[1] "\"产品\",\"销量\",\"单价\""
[2] "\"产品A\",120,9.9"
[3] "\"产品B\",85,15.8"
[4] "\"产品C\",150,5.6"
R Language Examples