readr包是tidyverse的一部分,它提供了一种快速友好的方式来读取规则的矩形文件(如:csv,tsv,fwf等)。

安装

  1. # The easiest way to get readr is to install the whole tidyverse:
  2. install.packages("tidyverse")
  3. # Alternatively, install just readr:
  4. install.packages("readr")
  5. # Or the the development version from GitHub:
  6. # install.packages("devtools")
  7. devtools::install_github("tidyverse/readr")

使用指南

数据读入

使用readr读取数据需要指定两个内容:

  1. 整个文件的格式(csv、tsv、fwf)
  2. 文件中每一列的特定属性(double、integer、numeric)

一般来说readr会自动猜测每一列的属性,并且自动赋予其最合适的数据类型

readr提供了七个read_*函数,来适应不同格式文件的读取:

这些函数运行之后返回的是一个tibble对象,是data frame的进阶版

readr比较友好的是可以对 .gz, .bz2, .xz, .zip等文件自动解压,对 http://, https://, ftp://, ftps://等链接自动进行下载

数据类型转换

readr是将数据按照字符读入,然后自行判定数据的属性。因此readr提供了parse_*guess_parser()来判断和指定元素的属性:

判断属性
  1. guess_parser(c("a", "b", "c"))
  2. #> [1] "character"
  3. guess_parser(c("1", "2", "3"))
  4. #> [1] "double"
  5. guess_parser(c("1,000", "2,000", "3,000"))
  6. #> [1] "number"
  7. guess_parser(c("2001/10/10"))
  8. #> [1] "date"

指定属性

parse_*函数类似于as.numeric()等函数

  1. parse_integer(c("1", "2", "3"))
  2. #> [1] 1 2 3
  3. parse_double(c("1.56", "2.34", "3.56"))
  4. #> [1] 1.56 2.34 3.56
  5. parse_logical(c("true", "false"))
  6. #> [1] TRUE FALSE

一般来说parse_integerparse_double的判定方式比较严格,要求字符中不能包含除数字外的其他字符;readr提供了parse_number来更为灵活的读取数字,它会忽略掉字符串中的非数字字符。

  1. parse_number(c("0%", "10%", "150%"))
  2. #> [1] 0 10 150
  3. parse_number(c("$1,234.5", "$12.45"))
  4. #> [1] 1234.50 12.45

读取向量作为因子时,需要设定levels顺序

  1. parse_factor(c("a", "b", "a"), levels = c("a", "b", "c"))
  2. #> [1] a b a
  3. #> Levels: a b c

数据属性查看

可以使用spec_*等函数查看数据整体的列的属性

  1. x <- spec_csv(readr_example("challenge.csv"))
  2. #> Parsed with column specification:
  3. #> cols(
  4. #> x = col_double(),
  5. #> y = col_logical()
  6. #> )

注意:readr默认只查看数据的前1000行,当后续数据的属性发生变化时,是不能检测到的,因此如果查看全局属性,需要添加参数guess_max

对于特定的tibble对象,则使用spec()查看

  1. spec(df1)
  2. #> cols(
  3. #> x = col_double(),
  4. #> y = col_logical()
  5. #> )
  6. spec(df2)
  7. #> cols(
  8. #> x = col_double(),
  9. #> y = col_date(format = "")
  10. #> )

更改默认属性

在读取数据时,可以使用col_type参数手动设置每列数据的属性

  1. df3 <- read_csv(
  2. readr_example("challenge.csv"),
  3. col_types = cols(
  4. x = col_double(),
  5. y = col_date(format = "")
  6. )
  7. )

常用的属性设置和缩写如下:

属性 简写 备注
col_logical() l containing only T, F, TRUE or FALSE
col_integer() i integers
col_double() d doubles
col_character() c everything else
col_factor(levels, ordered) f a fixed set of values
col_date(format = "") D with the locale’s date_format
col_time(format = "") t with the locale’s time_format
col_datetime(format = "") T ISO8601 date times
col_number() n numbers
col_skip() _ or - don’t import this column
col_guess() ? parse using the “best” type based on the input