←
PDF 179 / 520 - The name of the variable whose values form the column names. I call that the key, and here it
→
English · PDF 179
Original PDF page 179
中文 · PDF 179
  • 其值构成列名的变量的名称。我称之为键(key),这里是 year。
  • 其值分散到各个单元格中的变量的名称。我称之为值(value),这里是病例数。

这两个参数共同生成对 gather() 的调用:

table4a %>% gather(1999, 2000, key = "year", value = "cases") #> # A tibble: 6 × 3 #> country year cases #> #> 1 Afghanistan 1999 745 #> 2 Brazil 1999 37737 #> 3 China 1999 212258 #> 4 Afghanistan 2000 2666 #> 5 Brazil 2000 80488 #> 6 China 2000 213766

要整合的列使用 dplyr::select() 风格的表示法来指定。这里只有两列,所以我们逐个列出它们。注意 "1999" 和 "2000" 不是合法的语法名称,所以我们必须用反引号将它们括起来。要回顾其他选择列的方法,请参见第 51 页的“用 select() 选择列”。

在最终结果中,被整合的列被删除了,我们得到了新的键列和值列。除此之外,原始变量之间的关系得以保留。图 9-2 直观地展示了这一点。我们可以用类似的方式使用 gather() 来整理 table4b。唯一的区别是存储在单元格值中的变量:

table4b %>% gather(1999, 2000, key = "year", value = "population") #> # A tibble: 6 × 3 #> country year population #> #> 1 Afghanistan 1999 19987071 #> 2 Brazil 1999 172006362 #> 3 China 1999 1272915272 #> 4 Afghanistan 2000 20595360 #> 5 Brazil 2000 174504898 #> 6 China 2000 1280428583