R CSV Files Handling
Reading and writing data from a file is a very common task. R also provide functions for file handling like other programming language. In this tutorial, we will learn the csv file handling process using the R language.
Read CSV File
R provides read.csv() function to read data from a csv file. The syntax of read.csv() is as follows-
read.csv(file, header = TRUE, sep=",")
Here, file is the file path where the csv file is stored. If we have not mentioned the file path, it will take the current working directory. We can check the file path using getwd() function and also set the file path using setwd() function. The header parameter confirms the file header, by default it is true. In a CSV file,the data is stored with comma separated so the sep parameter specifies the variable split symbol.
Example
Suppose, there is a csv file name 'employee.csv', that is stored in the current working directory.
id,name,age,department
1,Dhyan,26,HR
2,Jorz,27,Finance
3,Mary,29,IT
4,Sinoy,32,IT
5,Lyo,30,Finance
The given code reads the 'employee.csv' file and produces the following results -
data <- read.csv('employee.csv', header=TRUE, sep=",")
print(data)
id.name.age.department
1 1,Dhyan,26,HR
2 2,Jorz,27,Finance
3 3,Mary,29,IT
4 4,Sinoy,32,IT
5 5,Lyo,30,Finance
We can also produce the above result in data frame-
data <- read.csv('employee.csv', header=TRUE, sep=",")
print(data.frame(data))
Writing into CSV File
R provides write.csv() function to create a new csv file or append in the existing csv file. The syntax of write.csv() is as follows -
write.csv(file)
Here, file is the filename which we want to create, by default it saves in the current working directory.
data <- data.frame(id=c(1:4),
+ name=c('Mary','Soy','Alexa','Roxy'),
+ class=5)
> result <- write.csv(data, file='student.csv')
> result
NULL