How To Write DataFrame To CSV In R

Let us first create our dataframe. For this exercise, I have downloaded the data from here...

I have unzipped the data and my data lives here data/indiaCovid19/covid_19_india.csv

Ok, now we can read our csv file in R with just simple command read.csv and passing option header=TRUE

In [1]:
df = read.csv('data/indiaCovid19/covid_19_india.csv',header = TRUE)

Let us check the number of rows in our dataframe.

In [2]:

Let us take a look at the first two rows of our dataframe.

In [3]:
A data.frame: 2 × 9
1130/01/206:00 PMKerala10001
2231/01/206:00 PMKerala10001

Ok let us write out dataframe in to csv file using R command write.csv.

In [4]:

Let us check if our file is present. In R, we can run unix commands by using system command. To print the output at the console, set intern=TRUE

In [5]:
system("ls -lrt MyData.csv",intern = TRUE)
'-rw-rw-r-- 1 root root 89701 Apr 29 22:32 MyData.csv'

Let us check the first two rows of our dataframe using cat command in R.

In [6]:
system('cat MyData.csv | head -2',intern=TRUE)
  1. '"","Sno","Date","Time","State.UnionTerritory","ConfirmedIndianNational","ConfirmedForeignNational","Cured","Deaths","Confirmed"'
  2. '"1",1,"30/01/20","6:00 PM","Kerala","1","0",0,"0",1'

Note, we got one extra column including row numbers too in the file. We can disable this by using option row.names=FALSE in write.csv in R.

In [7]:
write.csv(df,'MyData.csv',row.names = FALSE)

Now let us check the first two rows again.

In [8]:
system('cat MyData.csv | head -2',intern=TRUE)
  1. '"Sno","Date","Time","State.UnionTerritory","ConfirmedIndianNational","ConfirmedForeignNational","Cured","Deaths","Confirmed"'
  2. '1,"30/01/20","6:00 PM","Kerala","1","0",0,"0",1'

Wrap Up!

That is pretty much about writing dataframe to csv file in R.