Load packages
library(tidyverse)
Motivation
Importing data to R can cause headaches for newbies. For some, the concept of relative and absolute paths is new. That’s why I compiled here some recommendations on how to important data into R and on how to ditch the “what’s my path” problem.
Approach 1: Start an RStudio project
That’s an approach I generally recommend.
- Start an RStudio project.
- Put your code files and your data files in this very folder that you just defined as your RStudio project folder.
- Import the data without specifying any paths, eg.,
d <- read.csv("mydata.csv)
Approach 2: Import from an online source
That’s also really convenient – as long as someone has put the data online.
- Identify the URL of your data set, and copy it.
- Open up an R/Rmd script file and paste the URL to your import function, e.g,.
d <- read.csv("https://vincentarelbundock.github.io/Rdatasets/csv/reshape2/tips.csv")
Approach 3: Learn what a path means
It is crucial to distinguish between a relative path subdirectory/file.ext)
and an absolute path (user/me/some/dir/file.ext
). There are nice tutorials on that around. Worth to check out.
- Identify the location (path) of your data file on your computer.
- Copy it to the clipboard (depends on your operating system).
- Paste it into your import function, e.g,
d <- read.csv("/Users/sebastiansaueruser/datasets/tips.csv")
Example time – dataset tips
Assume we would like to import the dataset tips
(nice for teaching purposes). Assume you find its URL one the internet (see below). Then it is convenient to use read.csv()
or similar function to get the dataset into your R:
tips <- read.csv("https://vincentarelbundock.github.io/Rdatasets/csv/reshape2/tips.csv")