tidyr::pop_quiz:是否有更快/更透明的方法来重塑 anscombe 数据集?

tidyr::pop_quiz: is there a faster/ more transparent way to reshape the anscombe dataset?

我正在努力与 tidyr 相处融洽。有没有更好的方法来准备 anscombe 数据集以使用 ggplot2 进行绘图?具体来说,我不喜欢必须添加数据 (obs_num)。你会怎么做?

library(tidyverse)
library(datasets)

anscombe %>%
  mutate(obs_num = 1:n()) %>%
  gather(variable, value, -obs_num) %>%
  separate(variable, c("variable", "set"), 1) %>%
  spread(variable, value) %>%
  ggplot(aes(x = x, y = y)) +
  geom_point() +
  stat_smooth(method = "lm", se = FALSE, fullrange = TRUE) +
  facet_wrap(~set)

我认为您需要添加额外的列,以便在对 spread 的调用中唯一标识每个观察值。 Hadley 在 this SO question 的评论中对此进行了讨论。另一种方法是单独堆叠 xy 列,如下面的代码所示,但我不明白为什么这会比您的版本更好。事实上,如果存在 xy 值最终不对应的情况,情况可能会更糟:

bind_cols(anscombe %>% select(matches("x")) %>% gather(set, "x"),
          anscombe %>% select(matches("y")) %>% gather(key, "y")) %>%
  select(-key) %>%
  mutate(set = gsub("x", "Set: ", set))

另一种选择是使用基数 reshape,这更简洁:

anscombe %>% 
  reshape(varying=1:8, direction="long", sep="", timevar="set")