photo # 1. The goal of readr The goal of readr is to provide a fast and friendly way to read rectangular data from delimited files, such as comma-separated values (CSV) and tab-separated values (TSV).

readr giải quyết vấn đề quan trọng là phân tích cú pháp (Parsing) 1 tệp phẳng thành 1 tệp văn bản và biến nó thành 1 khối hình chữ nhật: trong đó mỗi cột là 1 phần thích hợp.

If you are new to readr, the best place to start is the data import chapter in R for Data Science.

Phân tích cú pháp (Parsing) diễn ra trong 3 giai đoạn cơ bản:

  1. Tệp phẳng được phân tích cú pháp thành một ma trận chuỗi hình chữ nhật.

  2. Loại của mỗi cột được xác định.

  3. Mỗi cột của chuỗi được phân tích cú pháp thành một vectơ có kiểu cụ thể hơn.

Each parse_() is coupled with a col_() function, which will be used in the process of parsing a complete tibble.

2. Xem cheatsheet cua readr/import data

import1 import1

3. Usage

readr is part of the core tidyverse, so you can load it with:

library(tidyverse)

Of course, you can also load readr as an individual package:

library(readr)

To read a rectangular dataset with readr, you combine two pieces: a function that parses the lines of the file into individual fields and a column specification.

library(readr)
chickens <- read_csv(readr_example("chickens.csv"))
## Rows: 5 Columns: 4
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## chr (3): chicken, sex, motto
## dbl (1): eggs_laid
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.

Note that readr prints the column types – the guessed column types, in this case. This is useful because it allows you to check that the columns have been read in as you expect. If they haven’t, that means you need to provide the column specification. This sounds like a lot of trouble, but luckily readr affords a nice workflow for this. Use spec() to retrieve the (guessed) column specification from your initial effort.

spec(chickens)
## cols(
##   chicken = col_character(),
##   sex = col_character(),
##   eggs_laid = col_double(),
##   motto = col_character()
## )
#> cols(
#>   chicken = col_character(),
#>   sex = col_character(),
#>   eggs_laid = col_double(),
#>   motto = col_character()
#> )

(This also allows you to access the full column specification if you’re reading a very wide file. By default, readr will only print the specification of the first 20 columns.)

Now you can copy, paste, and tweak this, to create a more explicit readr call that expresses the desired column types. Here we express that sex should be a factor with levels rooster and hen, in that order, and that eggs_laid should be integer.

chickens <- read_csv(
  readr_example("chickens.csv"),
  col_types = cols(
    chicken   = col_character(),
    sex       = col_factor(levels = c("rooster", "hen")),
    eggs_laid = col_integer(),
    motto     = col_character()
  )
)

Ví dụ khác:

df1 <- read_csv(readr_example("challenge.csv"))
## Rows: 2000 Columns: 2
## ── Column specification ────────────────────────────────────────────────────────
## Delimiter: ","
## dbl  (1): x
## date (1): y
## 
## ℹ Use `spec()` to retrieve the full column specification for this data.
## ℹ Specify the column types or set `show_col_types = FALSE` to quiet this message.
df1
## # A tibble: 2,000 × 2
##        x y     
##    <dbl> <date>
##  1   404 NA    
##  2  4172 NA    
##  3  3004 NA    
##  4   787 NA    
##  5    37 NA    
##  6  2332 NA    
##  7  2489 NA    
##  8  1449 NA    
##  9  3665 NA    
## 10  3863 NA    
## # … with 1,990 more rows
## # ℹ Use `print(n = ...)` to see more rows
spec(df1)
## cols(
##   x = col_double(),
##   y = col_date(format = "")
## )
df2 <- read_csv(
  readr_example("challenge.csv"), 
  col_types = list(
    x = col_double(),
    y = col_date(format = "")
  )
)

df3 <- read_csv(
  readr_example("challenge.csv"),
  col_types = cols(
    x = col_character(),
    y = col_date(format = "")
  )
)

df3
## # A tibble: 2,000 × 2
##    x     y     
##    <chr> <date>
##  1 404   NA    
##  2 4172  NA    
##  3 3004  NA    
##  4 787   NA    
##  5 37    NA    
##  6 2332  NA    
##  7 2489  NA    
##  8 1449  NA    
##  9 3665  NA    
## 10 3863  NA    
## # … with 1,990 more rows
## # ℹ Use `print(n = ...)` to see more rows

vignette(“readr”) gives an expanded introduction to readr https://readr.tidyverse.org/articles/readr.html

4. Alternatives

There are two main alternatives to readr: base R and data.table’s fread(). The most important differences are discussed below.

4.1. Base R

readr khác:

  • Đặt tên nhất quán cho các tham số (e.g. col_names and col_types không phải header và colClasses).

  • faster (up to 10x-100x) depending on the dataset.

  • để định dạng chuỗi theo mặc định và tự động phân tích cú pháp định dạng ngày/giờ phổ biến.

  • Có 1 thanh tiến trình, hữu ích trong trường hợp mất time tải dữ liệu.

  • Các chức năng hoạt động chính xác theo cùng 1 cách dù bất kể vị trí nào. To override the US-centric defaults, use locale().

4.2. data.table and fread()

data.table có một chức năng tương tự như read_csv () được gọi là fread (). So với hàm fread (), readr:

  • Đôi khi chậm hơn, đặc biệt là trên dữ liệu nặng dạng số ( numeric heavy data.)

  • Có thể tự động đoán một số tham số, nhưng về cơ bản khuyến khích đặc tả rõ ràng, ví dụ: dấu phân cách, hàng bị bỏ qua và hàng tiêu đề.

  • Tuân theo các quy ước trên toàn bộ ngăn nắp (tidyverse-wide conventions), chẳng hạn như trả về một mẩu tin nhỏ, một cách tiếp cận tiêu chuẩn để sửa chữa tên cột và một ngôn ngữ nhỏ phổ biến để chọn cột.