数据类型约束

R 中的数据清洗

Maggie Matsui

Content Developer @ DataCamp

课程概览

带放大镜的服务器与"诊断脏数据"

R 中的数据清洗

课程概览

带甲虫的服务器与"脏数据的副作用"

R 中的数据清洗

课程概览

圆形数据库配扫帚与闪光,表示干净数据

R 中的数据清洗

课程概览

诊断脏数据、脏数据的副作用、清理脏数据

第1章:常见数据问题

R 中的数据清洗

为何需要清洗数据?

 

数据科学流程:获取、探索与处理、提炼洞见、报告洞见

R 中的数据清洗

为何需要清洗数据?

 

人为与技术错误

R 中的数据清洗

为何需要清洗数据?

 

错误在流程中传播

R 中的数据清洗

数据类型约束

数据类型 示例
文本 名、姓、地址等
整数 订阅数、售出产品数等
小数 温度、汇率等
二元 是否已婚、新客户、是/否等
分类 婚姻状况、颜色等
日期 订单日期、出生日期等
R 数据类型
character
integer
numeric
logical
factor
Date
R 中的数据清洗

快速查看数据类型

sales <- read.csv("sales.csv")
head(sales)
  order_id revenue quantity
1     7432   5,454      494
2     7808   5,668      334
3     4893   4,062      259
4     6107   3,936       15
5     7661   1,067      307
6     5908   6,635      235
library(dplyr)
glimpse(sales)
Observations: 100
Variables: 3
$ order_id <dbl> 7432, 7808, ...
$ revenue  <chr> "$5454", "$5668", ...
$ quantity <dbl> 494, 334, ...
R 中的数据清洗

检查数据类型

is.numeric(sales$revenue)
FALSE
library(assertive)
assert_is_numeric(sales$revenue)
Error: is_numeric : sales$revenue is not of class 'numeric'; it has class 'character'.
assert_is_numeric(sales$quantity)


R 中的数据清洗

检查数据类型

逻辑检查:返回 TRUE/FALSE

  • is.character()
  • is.numeric()
  • is.logical()
  • is.factor()
  • is.Date()
  • ...

assertive 检查:为 FALSE 时报错

  • assert_is_character()
  • assert_is_numeric()
  • assert_is_logical()
  • assert_is_factor()
  • assert_is_date()
  • ...
R 中的数据清洗

为何数据类型重要?

class(sales$revenue)
"character"
mean(sales$revenue)
NA
Warning message:
In mean.default(sales$revenue) :
  argument is not numeric or logical: returning NA
R 中的数据清洗

逗号问题

sales$revenue
"5,454" "5,668" "4,062" "3,936" "1,067" ...

R 中的数据清洗

字符转数值

library(stringr)
revenue_trimmed = str_remove(sales$revenue, ",")

revenue_trimmed
"5454" "5668" "4062" "3936" "1067" ...
as.numeric(revenue_trimmed)
5454 5668 4062 3936 1067 ...
R 中的数据清洗

整合应用

sales %>%
  mutate(revenue_usd = as.numeric(str_remove(revenue, ",")))
# A tibble: 100 x 4
   order_id revenue quantity revenue_usd
      <dbl> <chr>      <dbl>       <dbl>
 1     7432 5,454        494        5454
 2     7808 5,668        334        5668
 3     4893 4,062        259        4062
 4     6107 3,936         15        3936
 5     7661 1,067        307        1067
# ... with 95 more rows
R 中的数据清洗

同一函数,不同结果

mean(sales$revenue)
NA
Warning message:
In mean.default(sales$revenue) :
  argument is not numeric or logical: returning NA
mean(sales$revenue_usd)
5361.4
R 中的数据清洗

转换数据类型

  • as.character()
  • as.numeric()
  • as.logical()
  • as.factor()
  • as.Date()
  • ...
R 中的数据清洗

注意:factor 转 numeric

product_type
1000 1000 3000 2000 3000
Levels: 1000 2000 3000
class(product_type)
"factor"
as.numeric(product_type)
1 1 3 2 3
as.numeric(as.character(product_type))
1000 1000 3000 2000 3000
R 中的数据清洗

开始练习吧!

R 中的数据清洗

Preparing Video For Download...