R code to read and write from/to CSV file

In R, there are multiple ways to read and write CSV files. One approach is using the built-in read.csv() function for reading data from a CSV file and the write.csv() function for writing data to a new CSV file.

Another approach is to utilize the readr package, which offers efficient CSV file reading with the read_csv() function and CSV writing with the write_csv() function.

Using built-in functions:

# Sample data to be written
csv_data <- data.frame(
  Name = c("Apple", "Banana", "Mango", "Pineapple"),
  Age = c(35, 20, 28, 56)
)

# Write data to a new CSV file
write.csv(csv_data, "new_data.csv", row.names = FALSE)

# Read data from the CSV file
data <- read.csv("new_data.csv")

The “row.names = FALSE” argument is used to exclude row names from being written to the CSV file.

Using the readr package:

# Install and load the readr package
if (!require("readr")){
  install.packages("readr")  
}
library(readr)

# Sample data to be written
csv_data <- data.frame(
  Name = c("Apple", "Banana", "Mango", "Pineapple"),
  Age = c(35, 20, 28, 56)
)

# Write data to a new CSV file 
write_csv(csv_data, "new_data.csv")

# Read data from the CSV file
data <- read_csv("new_data.csv", show_col_types=FALSE)

The “show_col_types=FALSE” argument does not show the guessed column types.

These examples demonstrate two different approaches to reading and writing data from/to CSV files in R. Depending on your specific needs and preferences, you can choose the method that best suits your requirements.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.