←
PDF 188 / 520 Because these explicit missing values may not be important in other representations of the data,
→
English · PDF 188
Original PDF page 188
中文 · PDF 188

由于这些显式缺失值在数据的其他表示形式中可能并不重要,你可以在 gather() 中设置 na.rm = TRUE,将显式缺失值变为隐式:

stocks %>% spread(year, return) %>% gather(year, return, 2015:2016, na.rm = TRUE) #> # A tibble: 6 × 3 #> qtr year return #> * #> 1 1 2015 1.88 #> 2 2 2015 0.59 #> 3 3 2015 0.35 #> 4 2 2016 0.92 #> 5 3 2016 0.17 #> 6 4 2016 2.66

在整洁数据中将缺失值显式化的另一个重要工具是 complete():

stocks %>% complete(year, qtr) #> # A tibble: 8 × 3 #> year qtr return #> #> 1 2015 1 1.88 #> 2 2015 2 0.59 #> 3 2015 3 0.35 #> 4 2015 4 NA #> 5 2016 1 NA #> 6 2016 2 0.92 #> # ... 还有 2 行

complete() 接受一组列,并找出所有唯一的组合。然后它会确保原始数据集包含所有这些值,并在必要时填入显式的 NA。

还有一个处理缺失值的重要工具你应该了解。有时当数据源主要用于数据录入时,缺失值表示应将前一个值向前填充:

treatment <- tribble( ~ person, ~ treatment, ~response, "Derrick Whitmore", 1, 7, NA, 2, 10, NA, 3, 9, "Katherine Burke", 1, 4 )