The most obvious way, the data scientists store the data is in Excel sheets. R programming language and its packages are designed to access data from Excel sheets. Users frequently find it more straightforward to save their data in comma-separated values files (CSV) and then use R’s inbuilt functionality to manage the data.
One of the best and most reliable ways of getting data into R is to use CSV files. Let’s see how to read csv files in R.
Read CSV files in R
To read the CSV files in R, use the read.csv() function.
Let’s say you have the following data.csv file.
show,service,season wandavision,disneyplus,1 barry,HBOMax,3
To open and read the CSV file, use the read.csv() function.
df <- read.csv("data.csv") df
show service season 1 wandavision disneyplus 1 2 Barry HBOMax 3
So, you can read the CSV files in R using the read.csv() function. Let’s see how to write CSV files.
write.csv() Function in R
The write.csv() is an inbuilt R function that saves the summaries of partitioned breeding values to CSV files on disk to analyze processing with other software further or saving results.
write.csv(x, file, traitsAsDir = FALSE, csv2 = TRUE, row.names = FALSE, ...)
x: It is an AlphaPart, the object returned from AlphaPart function or summaryAlphaPart, the object returned from the summary.AlphaPart function.
file: It is a character file name with or without a .csv extension, e.g., both “file” and “file.csv” are valid.
traitsAsDir: Logically, the result should be saved within trait folders; the construction is a file.path(dirname(), trait, basename()); folders are created if they do not exist.
csv2: It is a Logical export using write.csv2 or write.csv.
row.names: It is a Logical, export row names as well?
How to Export DataFrame to CSV in R
Let’s export a data frame to CSV in R step by step.
Step 1: Create a data frame
To create a DataFrame in R, use the data.frame() function.
df <- data.frame( service_id = c(1:5), service_name = c("Netflix", "Disney+", "HBOMAX", "Hulu", "Peacock"), service_price = c(18, 10, 15, 7, 12), stringsAsFactors = FALSE ) df
service_id service_name service_price 1 1 Netflix 18 2 2 Disney+ 10 3 3 HBOMAX 15 4 4 Hulu 7 5 5 Peacock 12
Step 2: Use the write.csv() function to Export the Data Frame to CSV
Pass the data frame to the write.csv() function to export the data to the CSV file.
df <- data.frame( service_id = c(1:5), service_name = c("Netflix", "Disney+", "HBOMAX", "Hulu", "Peacock"), service_price = c(18, 10, 15, 7, 12), stringsAsFactors = FALSE ) write.csv(df, "shows.csv", row.names = FALSE) cat("The data frame is exported", "\n")
The data frame is exported
And you can see in your current working directory that there will be a file created called shows.csv.
That is it. We successfully exported CSV from the R data frame.