←
PDF 181 / 520 #> 6 Brazil 1999 population 172006362 #> # ... with 6 more rows
→
English · PDF 181
Original PDF page 181
中文 · PDF 181

#> 6 Brazil 1999 population 172006362 #> # ... with 6 more rows

要整理这些数据,我们首先以类似 gather() 的方式分析其表示形式。不过这一次,我们只需要两个参数:

  • 包含变量名的列,即键列。在这里,它是 type。
  • 包含构成多个变量的值的列,即值列。在这里,它是 count。

弄清楚这些之后,我们就可以使用 spread(),如下面的程序代码所示,其可视化效果见图 9-3:

spread(table2, key = type, value = count) #> # A tibble: 6 × 4 #> country year cases population #> * #> 1 Afghanistan 1999 745 19987071 #> 2 Afghanistan 2000 2666 20595360 #> 3 Brazil 1999 37737 172006362 #> 4 Brazil 2000 80488 174504898 #> 5 China 1999 212258 1272915272 #> 6 China 2000 213766 1280428583

Figure 2: A graphic showing the relationship between country country coverage and population coverage for the year 1999. The graph is divided into three sections by country coverage value. The top section shows country coverage values for Afghanistan (1999), Brazil (1999), and China (1999). The middle section shows country coverage values for Brazil (2000), China (2000), and China (2000). The bottom section shows country coverage values for Afghanistan (2000), Brazil (2000), and China (2000). Arrows indicate the corresponding country coverage values for the year 2000.

国家 年份 键 值 国家 年份 病例 人口
阿富汗 1999 病例 745 阿富汗 1999 745 19987071
阿富汗 1999 人口 19987071 阿富汗 2000 269 20595360
阿富汗 2000 病例 2666 巴西 1999 37737 172006362
阿富汗 2000 人口 20595360 巴西 2000 80488 1745044898
巴西 1999 病例 37737 中国 1999 212258 1272915272
巴西 1999 人口 172006362 中国 2000 213766 1280428583
巴西 2000 病例数 80488
巴西 2000 人口 1745044898
中国 1999 病例数 212258
中国 1999 人口 1272915272
中国 2000 病例数 213766
中国 2000 人口 1280428583

图 9-3. 对 table2 进行 spread 操作使其变得整洁

正如你可能从它们共同的 key 和 value 参数中猜到的那样,spread() 和 gather() 是互补的。gather() 使宽表变得更窄更长;spread() 使长表变得更短更宽。