【问题标题】:Using dplyr, how to pipe or chain to plot()?使用 dplyr,如何通过管道或链接到 plot()?
【发布时间】:2015-01-12 11:15:05
【问题描述】:

我是 dplyr() 包的新手,并试图将它用于我的可视化任务。我可以将我的数据通过管道传输到 ggplot(),但无法使用 plot() 来做到这一点。我遇到了this post,包括 cmets 中的答案在内的答案对我不起作用。

代码 1:

emission <- mynei %>%
    select(Emissions, year) %>%
    group_by(year) %>%
    summarise (total=sum(Emissions))

emission %>%
    plot(year, total,.)

我收到以下错误:

Error in plot(year, total, emission) : object 'year' not found

代码 2:

mynei %>%
    select(Emissions, year) %>%
    group_by(year) %>%
    summarise (total=sum(Emissions))%>%
    plot(year, total, .)

这也不起作用并返回相同的错误。

有趣的是,我提到的帖子中的解决方案适用于相同的数据集,但不适用于我自己的数据。但是,我可以使用 emission$yearemission$total 创建绘图。

我错过了什么吗?

【问题讨论】:

  • 如您链接的问题的答案所示,plot.formula 具有 data 参数。所以你需要使用plot(total ~ year, .)
  • @aosmith 感谢您的澄清。它奏效了。
  • 这也可以在不指定 . 的情况下工作 - 所以你可以使用例如plot(total ~ year).

标签: r plot dplyr piping


【解决方案1】:

plot.default 不接受数据参数,所以最好的办法是通过管道传递给with

mynei %>%
    select(Emissions, year) %>%
    group_by(year) %>%
    summarise (total=sum(Emissions))%>%
    with(plot(year, total))

如果有人错过了@aosmith 对该问题的评论,plot.formula确实有一个数据参数,但当然formula 是第一个参数,所以我们需要使用.将数据放在正确的位置。所以另一种选择是

... %>%
  plot(total ~ year, data = .)

当然,ggplotdata 作为第一个参数,所以要使用ggplot 这样做:

... %>%
  ggplot(aes(x = year, y = total)) + geom_point()

lattice::xyplot 就像plot.formula:有一个数据参数,但不是第一个,所以:

... %>% 
  xyplot(total ~ year, data = .)

如果data 不是第一个参数,请查看文档并确保使用.。如果根本没有 data 参数,则使用 with 是一个很好的解决方法。

【讨论】:

    【解决方案2】:

    作为替代方案,您可以使用magrittr 中的%$% 运算符来直接访问数据框的列。例如:

    iris %$%
      plot(Sepal.Length~Sepal.Width)
    

    当您需要将 dplyr 链的结果提供给基本 R 函数(例如 tablelmplot 等)时,这非常有用。它还可以用于从数据框中提取列作为向量,例如:

    iris %&gt;% filter(Species=='virginica') %$% Sepal.Length

    这与:

    iris %&gt;% filter(Species=='virginica') %&gt;% pull(Sepal.Length)

    【讨论】:

      猜你喜欢
      • 2017-11-25
      • 1970-01-01
      • 2018-09-01
      • 1970-01-01
      • 2015-04-14
      • 2023-03-22
      • 2022-01-19
      • 2015-11-07
      • 1970-01-01
      相关资源
      最近更新 更多