0

Here is the code I am trying to run and it is giving me the above mentioned error:

dt %>% filter(brand=="volkswagen") %>% 
  filter(Agecat!="NA") %>% 
  group_by(model,Agecat) %>% 
  summarise(Totaldays2close=sum(Days2close)) %>% 
 ## spread(Agecat,Totaldays2close) %>% 
 ## write_csv("Export.csv")


ggplot()+
    geom_col(mapping = aes(x=Agecat,y=Days2close))

Where Agecat is categorical variable and Days2close is no. of days required to close deal. Can you suggest how to avoid and why this error is coming?

msr_003
  • 1,205
  • 2
  • 10
  • 25
  • 2
    Difficult to answer without [seeing some or all](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) of `dt`. – neilfws Aug 07 '18 at 05:45
  • 1
    If you're using `summarise` to create `Totaldays2close`, then `Days2close` may no longer be present in the new dataframe, thus your passing ggplot a column that doesn't exist – Conor Neilson Aug 07 '18 at 05:50
  • 1
    Are you sure that `%>%` should be there at the end of your `summarise` function? – msr_003 Aug 07 '18 at 06:13
  • The pipe (`%>%`) ad the end of the `summarise()` passes the resulting data.frame to `ggpot()`, so it's fine. However, as @ConorNeilson points it out, the `summarise()` function does drop columns that are not summarising or grouping column. You should use `mutate()`instead to keep your original data and add your summarising column to all rows. – Hobo Sheep Aug 07 '18 at 08:24

1 Answers1

0

You don't want to summarise at it drops columns that are not grouping or summarising columns. Mutate allows you to compute a summary statisitc per group while keeping the rest of the data:

dt %>% filter(brand=="volkswagen") %>% 
  filter(Agecat!="NA") %>% 
  group_by(model,Agecat) %>% 
  mutate(Totaldays2close=sum(Days2close)) %>% 
ggplot()+
    geom_col(mapping = aes(x=Agecat,y=Days2close))

It should work now.

Hobo Sheep
  • 389
  • 2
  • 11
  • Thanks Hobo Sheep, it is working now. Conor Neilson your reasoning is also correct, when I dropped summarise line code then also it started working. – Abhinav Srivastava Aug 07 '18 at 09:03
  • Glad it worked. Could you please accept the answer (tick mark below votes) so people know it's solved. Cheers. – Hobo Sheep Aug 07 '18 at 11:32