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 such as 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:
xThe data frame or matrix to be written.
fileThe output file path.
row.namesWhether to save row names, default is TRUE. It is recommended to set it to FALSE to avoid extra columns.
Example
# Create 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 to 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 original written content
lines <- readLines("temp_products.csv")
print("CSV content:")
print(lines)
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 to 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 original written content
lines <- readLines("temp_products.csv")
print("CSV content:")
print(lines)
The output of the above code 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"Other Extensions
R Language Example