CSV Files
Thus far in our course, we have primarily utilized the iris dataset,
which is readily available in every R environment through the simple
command data(iris)
. As you continue to expand your R
programming skills after this course, you will inevitably engage with
a variety of other datasets. In this lesson, we delve into the process
of importing data stored in a CSV file format, a common
format for data handling.
CSV - an acronym for Comma Separated Value - stores data by separating values with commas. This preference stems from its straightforward structure and universal readability across modern programming languages.
Creating a CSV file
To see what a CSV file looks like, let's save a dataframe as a CSV file.
This task is accomplished through the write.csv
function,
which necessitates two parameters: the designated filename and
the dataframe to be saved.
"","season","avg_temp"
"1",'spring',50
"2",'summer',70
"3",'autumn',61
"4",'winter',25
Although the writing process doesn't provide a visible output, it structures the file with the header/column names in the first row, the index/row number as the first column then the contents of the dataframe are written, separating all values with commas. In the code block above, we wrote out what the text in this file looks like. Up next, we will explore how to load this file back into memory.
Reading a CSV file
The process of reading a CSV file mirrors that of writing one.
Leveraging the read.csv
function, we input the
filename as the primary argument. To ensure clarity during this
demonstration, we will store the loaded dataframe in a new object
termed df_2, distinguishing it from the previously
created df.
However, upon execution, we notice an unexpected X
column. This addition occurred because R interpreted the first
column of row indices as a data column, defaulting to X
as its header. To correctly specify this column as the row names,
we introduce an additional parameter to the read.csv
function.
Excellent, with this understanding, you are now equipped to both read and write CSV files efficiently!
As we approach the culmination of this course, the next lesson will guide you through a final project, putting into practice the skills acquired throughout our sessions.