R Reading Data
Most analyses start by loading data from a file. The workhorse for text files is read.csv() (and its general form read.table()), which returns a data frame.
On your own computer you would read a file from disk or a URL:
sales <- read.csv("data/sales.csv")
sales <- read.csv("https://example.com/sales.csv")The playground can't access files, so in this lesson we pass the CSV as text with the text argument. Everything else works exactly the same.
A first CSV
csv <- "product,price,qty
Notebook,3.50,12
Pen,1.20,40
Backpack,24.99,3"
sales <- read.csv(text = csv)
sales
str(sales) product price qty
1 Notebook 3.50 12
2 Pen 1.20 40
3 Backpack 24.99 3
'data.frame': 3 obs. of 3 variables:
$ product: chr "Notebook" "Pen" "Backpack"
$ price : num 3.5 1.2 25
$ qty : int 12 40 3
The first line becomes the column names (header = TRUE is the default), and each column gets a sensible type automatically.
Separators and decimal marks
Not every "CSV" uses commas. Many European files use ; as a separator and , as the decimal mark; read.csv2() handles that. For tabs use sep = "\t" (or read.delim()):
eu <- "city;temp
Berlin;12,5
Madrid;19,1"
read.csv2(text = eu)
tsv <- "id\tscore\n1\t88\n2\t93"
read.delim(text = tsv) city temp
1 Berlin 12.5
2 Madrid 19.1
id score
1 1 88
2 2 93
Useful arguments
| Argument | Purpose |
|---|---|
header = FALSE |
the file has no header row |
col.names = c(...) |
set column names |
colClasses = c(...) |
force column types |
na.strings = c("", "NA", "-") |
values to treat as missing |
skip = n |
skip the first n lines |
nrows = n |
read only n rows |
stringsAsFactors = TRUE |
turn text columns into factors |
comment.char = "#" |
ignore comment lines |
messy <- "# exported 2024-05-01
id,name,score
1,Ana,88
2,Ben,-
3,,75"
df <- read.csv(text = messy, comment.char = "#",
na.strings = c("", "-"), colClasses = c("integer", "character", "numeric"))
df
colSums(is.na(df)) id name score
1 1 Ana 88
2 2 Ben NA
3 3 <NA> 75
id name score
0 1 1
Inline data with a header-less file
raw <- "2024-01-05 120
2024-01-06 95
2024-01-07 143"
visits <- read.table(text = raw, col.names = c("day", "visitors"))
visits$day <- as.Date(visits$day)
str(visits)
mean(visits$visitors)'data.frame': 3 obs. of 2 variables:
$ day : Date, format: "2024-01-05" "2024-01-06" ...
$ visitors: int 120 95 143
[1] 119.3333
Checking what you loaded
Always inspect fresh data before analysing it:
csv <- "region,month,revenue
North,Jan,1200
North,Feb,1350
South,Jan,980
South,Feb,1105
East,Jan,
East,Feb,1010"
d <- read.csv(text = csv, stringsAsFactors = TRUE)
dim(d)
summary(d)[1] 6 3
region month revenue
East :2 Feb:3 Min. : 980
North:2 Jan:3 1st Qu.:1010
South:2 Median :1105
Mean :1129
3rd Qu.:1200
Max. :1350
NAs :1
summary() immediately reveals the missing revenue value and shows that region and month were read as factors.
Writing data
write.csv() saves a data frame. Without a file name it writes to the console, which is a handy way to see the result:
out <- data.frame(name = c("Ana", "Ben"), total = c(12.5, 8))
write.csv(out, row.names = FALSE)
write.csv(out, stdout(), row.names = FALSE, quote = FALSE)"name","total"
"Ana",12.5
"Ben",8
name,total
Ana,12.5
Ben,8
On your computer, write.csv(out, "results.csv", row.names = FALSE) writes a file. Leave out row.names = FALSE and you'll get an extra unnamed column of row numbers.
Tip: For other formats you need packages:
readxlfor Excel,havenfor SPSS/Stata/SAS,jsonlitefor JSON,DBIfor databases, andreadr/data.tablefor very fast CSV reading.
Test yourself
Which function reads a semicolon-separated file with comma decimals?
- read.csv()
- read.csv2()
- read.delim()
- readLines()
How do you treat the string "n/a" as missing when reading?
- missing = "n/a"
- na.strings = "n/a"
- na.rm = TRUE
- skip = "n/a"
What does read.csv(text = s) do?
- Reads a file named s
- Parses the CSV content in the string s
- Writes s to a file
- Prints s