CSV Files in R

In R can read and write into various file formats like csv, excel,json, xml etc. The csv file is a text file in which the values in the columns are separated by a comma. read.csv() function is used to read a CSV file  in your working directory. Similarly, write.csv() function is used to write the csv file.  You can download the sample data set  by clicking here and then read it using read.csv() function.

Download the IRIS Data Set

Reading a CSV File in R:

 

mydata <- read.csv(file="http://makemeanalyst.com/wp-content/uploads/2017/06/iris.csv", header=TRUE, sep=",")
head(mydata)
dim(mydata)
summary(mydata)

Output:

> head(mydata)
X Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 1 5.1 3.5 1.4 0.2 setosa
2 2 4.9 3.0 1.4 0.2 setosa
3 3 4.7 3.2 1.3 0.2 setosa
4 4 4.6 3.1 1.5 0.2 setosa
5 5 5.0 3.6 1.4 0.2 setosa
6 6 5.4 3.9 1.7 0.4 setosa
> dim(mydata)
[1] 150 6
> summary(mydata)
X Sepal.Length Sepal.Width Petal.Length Petal.Width Species
Min. : 1.00 Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100 setosa :50
1st Qu.: 38.25 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300 versicolor:50
Median : 75.50 Median :5.800 Median :3.000 Median :4.350 Median :1.300 virginica :50
Mean : 75.50 Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199
3rd Qu.:112.75 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
Max. :150.00 Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500

Writing into a CSV File:

The write.csv() function is used to create the csv file.

mydata <- read.csv(file="http://makemeanalyst.com/wp-content/uploads/2017/06/iris.csv", header=TRUE, sep=",")
t<-tail(mydata)

t
write.csv(t,"Iris_tail.csv", row.names = FALSE)

Output:

X Sepal.Length Sepal.Width Petal.Length Petal.Width Species
145 145 6.7 3.3 5.7 2.5 virginica
146 146 6.7 3.0 5.2 2.3 virginica
147 147 6.3 2.5 5.0 1.9 virginica
148 148 6.5 3.0 5.2 2.0 virginica
149 149 6.2 3.4 5.4 2.3 virginica
150 150 5.9 3.0 5.1 1.8 virginica

If you are interested you can check the more about Data Input and Data Output.

Reading and Writing Data to and from R

JSON Files in R