Open In App

Add header to file created by write.csv in R

Last Updated : 01 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In R programming, the write.csv() function is used to save data frames as comma-separated values (CSV) files. When a CSV file is created using the write.csv() function, it does not contain a header by default. However, it is often useful to include a header row in the CSV file that contains the names of the variables in the data frame.

In this article, We will explain how to add a header to a file created by write.csv() in R.

Adding Header to a CSV file in R using write.csv() Function

To add headers to the columns of a CSV file in R, we will use write.csv() function. Let us first understand its syntax.

Syntax:
write.csv(data, path, row.names, col.names)

Parameters:

  • data: the data set to be added to the CSV file
  • path: the path where the file is to be created
  • row.names: name of the rows in a CSV file. When set to FALSE, the CSV file won’t have a row name
  • col.names: name of the columns in a CSV file. We can specify our own column names to the columns.

Steps to add Header to a CSV file in R

Follow the below steps to create a CSV file and then add a header to its columns.

Step 1: Create a CSV file

This code creates a data frame df with two columns x and y. The x column contains the values 1, 2, and 3, and the y column contains the values 4, 5, and 6. The write.csv() function is then used to write the data frame to a CSV file named “file.csv”. The row.names argument is set to FALSE to exclude row names from the output, and the col.names argument is set to TRUE to include column names in the output.

R




# Create a data frame
df <- data.frame(x = 1:3, y = 4:6)
 
# Write the data frame to a CSV file with header
write.csv(df, "file.csv", row.names = FALSE, col.names = TRUE)


Output:

A simple CSV file

Step 2: Add Header to CSV file

This code reads the CSV file “file.csv” into a new data frame df. The header variable is then created as a character vector containing the column names “name1” and “name2”. The names function is used to set the column names of df to the values in the header. Finally, the write.csv function is used to write the modified data frame back to the CSV file “file.csv”. The sep argument is set to “,” to specify that the file is comma-separated, and the append argument is set to FALSE to overwrite the existing file.

R




# Read the CSV file into a data frame
df <- read.csv("file.csv")
 
# Add a header to the data frame
header <- c("name1", "name2")
names(df) <- header
 
# Write the data frame to the CSV file with header
write.csv(df, "file.csv", sep = ",", row.names = FALSE, col.names = TRUE, append = FALSE)


Output:

Header added to the CSV file



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads