2

我正在努力适应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)
4

1 回答 1

2

我认为您需要添加额外的列才能唯一标识调用中的每个观察spread。Hadley 在对此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))

另一种选择是使用 base reshape,它更简洁:

anscombe %>% 
  reshape(varying=1:8, direction="long", sep="", timevar="set")
于 2016-10-19T17:21:46.147 回答