R Programming language - R Read and Write CSV

www.igi‮aeditf‬.com

In R programming language, you can read and write CSV (Comma-Separated Values) files using the built-in functions read.csv() and write.csv() respectively. CSV files are a common file format for storing and sharing data in a tabular format.

Reading CSV Files

The read.csv() function reads a CSV file and returns a data frame object. Here's an example:

# Read a CSV file
mydata <- read.csv("mydata.csv")

# View the first few rows of the data
head(mydata)

In this example, we use the read.csv() function to read a CSV file called mydata.csv and store the resulting data frame in the mydata variable. We then use the head() function to view the first few rows of the data.

By default, read.csv() assumes that the first row of the CSV file contains column names. If your CSV file does not have column names, you can set the header argument to FALSE:

# Read a CSV file without headers
mydata <- read.csv("mydata.csv", header = FALSE)

# View the first few rows of the data
head(mydata)

Writing CSV Files

The write.csv() function writes a data frame to a CSV file. Here's an example:

# Write a data frame to a CSV file
write.csv(mydata, "mydata.csv", row.names = FALSE)

In this example, we use the write.csv() function to write the mydata data frame to a CSV file called mydata.csv. The row.names argument is set to FALSE to exclude row names from the output.

By default, write.csv() separates values in the CSV file with commas. If you want to use a different separator, you can set the sep argument to the desired character. For example, to use tabs as the separator, you would set sep = "\t":

# Write a data frame to a tab-separated file
write.csv(mydata, "mydata.tsv", row.names = FALSE, sep = "\t")

In this example, we use the write.csv() function to write the mydata data frame to a tab-separated file called mydata.tsv. The sep argument is set to "\t" to specify tab-separated values.