Dave Walters
Dave Walters

Reputation: 21

How to use chaining in dplyr to access "internal" variables

New to (d)plyr, working through chaining, a basic question - for the hflights example, want to use one of these embedded vars to make a basic plot:

hflights %>%
    group_by(Year, Month, DayofMonth) %>%
    select(Year:DayofMonth, ArrDelay, DepDelay) %>%
    summarise(
        arr = mean(ArrDelay, na.rm = TRUE),
        dep = mean(DepDelay, na.rm = TRUE)
    ) %>%
    plot (Month, arr)

Returns:

Error in match.fun(panel) : object 'arr' not found

I can make this work going step by step, but can I get where I want to go somehow with %>%...

Upvotes: 2

Views: 465

Answers (1)

hadley
hadley

Reputation: 103898

plot() doesn't work that way. The closest you could get is:

library(dplyr)
library(hflights)

summary <- hflights %>%
  group_by(Year, Month, DayofMonth) %>%
  select(Year:DayofMonth, ArrDelay, DepDelay) %>%
  summarise(
    arr = mean(ArrDelay, na.rm = TRUE),
    dep = mean(DepDelay, na.rm = TRUE)
  ) 

summary %>%
  plot(arr ~ Month, .)

Another alternative is to use ggvis, which is explicitly designed to work with pipes:

library(ggvis)
summary %>%
  ggvis(~Month, ~arr)

Upvotes: 3

Related Questions