R language can read and write data into various file formats like csv, excel xml etc. In this R programming tutorial, I’ll show you how to read CSV in R. Here I’ll also include simple example to demonstrate this concept clearly. We can read csv file in two ways. I will show you both of them.
At first we have to check in which directory which directory the R workspace is pointing. We can check this by getwd()function. After that, we have to set new working directory for R. To do this we have to use setwd()function.
# Get and print current working directory.
print(getwd())
After executing the code, it will produce the result below:
[1] "/web/com/1441086124_2016"
Now we will set our new directory:
# Set current working directory.
setwd("C:\Users\CrazyProgrammer\Desktop")
I have an input.csv file. It has 5columns and 8 rows.
Following is a simple example of read.csv()function to read a CSV file available in your current working directory –
data <- read.csv("file_name.csv")
Now we are going to read our csv file and then print it
data <- read.csv("input.csv")
print(data)
When we will execute the above code, our output looks like this −
id, name, salary, start_date, dept
1 1 Rick 623.30 2012-01-01 IT
2 2 Dan 515.20 2013-09-23 Operations
3 3 Michelle 611.00 2014-11-15 IT
4 4 Ryan 729.00 2014-05-11 HR
5 5 Gary 843.25 2015-03-27 Finance
6 6 Nina 578.00 2013-05-21 IT
7 7 Simon 632.80 2013-07-30 Operations
8 8 Guru 722.50 2014-06-17 Finance
Now I am going to discuss about the easiest way to read a file from .csv.
Syntax
read.csv('Path where your CSV file is located on your computer\File_Name.csv')
If we want data container header, then we need to write like this
read.csv('Path where your CSV file is located on your computer\File_Name.csv', header = TRUE)
Example of Read in CSV R
read.csv(' C:\Users\CrazyProgrammer\Desktop\input.csv')
Our output looks like—
1 1 Rick 623.30 2012-01-01 IT
2 2 Dan 515.20 2013-09-23 Operations
3 3 Michelle 611.00 2014-11-15 IT
4 4 Ryan 729.00 2014-05-11 HR
5 5 Gary 843.25 2015-03-27 Finance
6 6 Nina 578.00 2013-05-21 IT
7 7 Simon 632.80 2013-07-30 Operations
8 8 Guru 722.50 2014-06-17 Finance
If we want data container header, then
read.csv(' C:\Users\CrazyProgrammer\Desktop\input.csv', header = TRUE))
Now, our output looks like–
id, name, salary, start_date, dept
1 1 Rick 623.30 2012-01-01 IT
2 2 Dan 515.20 2013-09-23 Operations
3 3 Michelle 611.00 2014-11-15 IT
4 4 Ryan 729.00 2014-05-11 HR
5 5 Gary 843.25 2015-03-27 Finance
6 6 Nina 578.00 2013-05-21 IT
7 7 Simon 632.80 2013-07-30 Operations
8 8 Guru 722.50 2014-06-17 Finance
Related Post:
How to Read text file in R?
Today we have learned about how to read CSV in R programming language. I hope you guys understood everything clearly. So, guys, that’s all about for today. Later we will discuss another topic of r programming language. Till then, take care. Happy Coding