R CSV Files
We shall learn R functions to :
- R Read CSV Files
- R Process CSV Files
- R Write CSV Files
Example of a CSV File, that we use in the examples going forward, is given below :sampleCSV.csv
sampleCSV.csv
Andrew,28,25.2
Mathew,23,10.5
Dany,49,11
Philip,29,21.9
John,38,44
Bing,23,11.5
Monica,29,45
You may refer R Working Directory to modify the path of R Workspace to point to the directory containing your input files (CSV Files).
Read CSV Files
CSV Files are those files with values separated by commas in each row. Each row corresponds to a record or observation.
Syntax of function to read CSV File in R programming language :
read.csv(<filename>)
Example to read CSV File in R programming language :
r_readCSVexample.R - R Script File #Example R program to read CSV File #set working directory - the directory containing csv file setwd("/home/arjun/workspace/r") #read csv file csvData = read.csv("sampleCSV.csv") #print the data type of csvData cat("CSV Data type : ",class(csvData), "\n\n") print(csvData) Terminal Output $ Rscript r_readCSVexample.R CSV Data type : data.frame name age income 1 Andrew 28 25.2 2 Adarsh 23 10.5 3 Dany 49 11.0 4 Philip 29 21.9 5 John 38 44.0 6 Bing 23 11.5 7 Monica 29 45.0
Please observe that the data of csv file is read to an R Data Frame.
Process data read from CSV Files
R programming language reads the CSV File to an R Dataframe. So, you may use all the R Data Frame functions to process the data.
Some of the examples are given below.
Example R program to retrieve rows based on a condition applied to column
From the csv file, we shall extract rows, whose income is equal to the maximum of income.
r_csv_analyze_data.R - R Script File # Example R program to analyze CSV File # set working directory - the directory containing csv file setwd("/home/arjun/workspace/r") # read csv file celebrities = read.csv("sampleCSV.csv") # retrieve rows based on a condition maxSalariedCelebrities = subset(celebrities, income==max(income)) # print the result print(maxSalariedCelebrities) Terminal Output $ Rscript r_csv_analyze_data.R name age income 7 Monica 29 45
Write transformed data to CSV Files
Once we extract the required data or transform the data which is in data frame, we may write data frame to a CSV File.
Example R program to write an R data frame to CSV File
We shall use the above example, where we extracted rows with maximum income, and write the resulting rows to a CSV File.
r_csv_write_data.R - R Script File # Example R program to write data to a CSV file # set working directory - the directory containing csv file setwd("/home/arjun/workspace/r") # read csv file celebrities = read.csv("sampleCSV.csv") # retrieve rows based on a condition maxSalariedCelebrities = subset(celebrities, income==max(income)) # write filtered data into a new CSV file. write.csv(maxSalariedCelebrities,"result.csv") Terminal Output Rscript r_csv_write_data.R
