Read a .csv file and Explore the Arguments

Let’s start by opening a .csv file containing information on the speeds at which cars of different colors were clocked in 45 mph zones in the four-corners states (car-speeds.csv). Download the file here. We will first use the built in read.csv() function, which reads the data in as a data frame, and assign the data frame to a variable (using <-, check the shortcut buttons) so that it is stored in R’s memory. Then we will explore some of the basic arguments that can be supplied to the function.

#First create a new directory called R_exercises in your home directory (~/) and set the working directory here (tip: you can make the directory using the Terminal tab in the console).

setwd("~/R_exercises/")
#Import the data and look at the first six rows
carSpeeds <- read.csv(file="car-speeds.csv") # Remember to use the autocomplete button, especially on the file names.
head(carSpeeds)
##   Color Speed     State
## 1  Blue    32 NewMexico
## 2   Red    45   Arizona
## 3  Blue    35  Colorado
## 4 White    34   Arizona
## 5   Red    25   Arizona
## 6  Blue    41   Arizona

The default for read.csv() is to set the header argument toTRUE. This means that the first row of values in the .csv is set as header information (column names). If your data set does not have a header, set the header argument to `FALSE:

#The first row of the data without setting the header argument:
carSpeeds[1,]
##   Color Speed     State
## 1  Blue    32 NewMexico
#The first row of the data if the header argument is set to FALSE:
carSpeeds <- read.csv(file="car-speeds.csv", header=FALSE)

carSpeeds[1,]
##      V1    V2    V3
## 1 Color Speed State

Another way to import dataset files into R

RStudio has a nice built-in feature which helps you importing files. Go to File -> Import Datasets -> From Text (readr). This requires that you have installed the readr package (comes with Tidyverse). You can also choose to import using base R functions (From Text (base)), but you have fewer options for tuning. Notice that you can also import other types of files, like excel files.