Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

R write.csv() Function - Writing CSV Files

R write.csv() Function - Writing CSV Files

R Language Examples R Language Examples

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:

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"

)

print

(

"Saved and read-back data:"

)

print

(

data

)

View the raw written content

lines

<-

readLines

(

"temp_products.csv"

)

print

(

"CSV content:"

)

print

(

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 R Language Examples