R CSV Files

In R it is possible to read data from files and write data to a file. R supports various formats for reading and writing like csv, excel, xml, etc.

Here, we will learn to read data from a csv (comma separated value) file and then write data into a csv file.

Getting and Setting the Working Directory

We can get the current working directory of R by using getwd() function.

We can also set the new working directory using setwd() function.

Create a CSV File

The csv file is text file in which the values in columns are separated by comma. Let’s create a CSV file. To create a csv file write the columns data separated by comma in notepad or any other text editor and save this file with the extension of .csv.

Let’s see an example to create a csv file as demo.csv:

Reading a CSV File

We can read a csv file through read.csv() function. This function will return the result in the form of data frame.

Example:

Output:

Analyzing the CSV File

Example 1: Find the number of rows and columns

We can find the number of columns and rows in the CSV file by using ncol() and nrow() function:

Output:

Example 2: Get the Maximum Salary

Output:

Example 3: Get the details of the person with maximum Salary

Output:

Example 4: Get the details of people working in Operations department

Output:

Example 5: Get the details of persons whose date of joining on or after 2018

Output:

Writing into a CSV File

write.csv() function is used to create a csv file from an existing data frame.

Example:

Output:

Here, row.names argument allows us to set the names of the rows in the output data file. Default value of this argument is TRUE. Since it does not know what else to name the rows, it resorts to using row numbers. To correct this we can set row.names to FALSE.

There is also a col.names argument, which can be used to set the name of columns for a data set without headers. If the dataset already had headers then a col.names argument will be ignored.

 Reference:
https://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html