5

How can I assign the value of a variable to a ggplot title after filtering the underlying dataframe 'in one go'.

library(tidyverse)

#THIS WORKS
d <- mtcars %>% 
  filter(carb==4)

d %>% 
  ggplot()+
  labs(title=paste(unique(d$carb)))+
  geom_bar(aes(x=am,
               fill=gear),
           stat="count")



#THIS DOESN'T WORK

mtcars %>% 
  filter(carb==4) %>% 
  ggplot()+
  labs(title=paste(data=. %>% distinct(carb) %>% pull()))+
  geom_bar(aes(x=am,
               fill=gear),
           stat="count")
#> Error in as.vector(x, "character"): cannot coerce type 'closure' to vector of type 'character'

#THIS ALSO DOESN'T WORK

mtcars %>% 
  filter(carb==3) %>% 
  ggplot()+
  labs(title=paste(.$carb))+
  geom_bar(aes(x=am,
               fill=gear),
           stat="count")
#> Error in paste(.$carb): object '.' not found

Created on 2020-04-23 by the reprex package (v0.3.0)

1 Answer 1

6

We can wrap the code block with {} and use .$

library(dplyr)
library(ggplot2)
mtcars %>% 
  filter(carb==4) %>% {
  ggplot(., aes(x = am, fill = gear)) +
       geom_bar(stat = 'count') +
       labs(title = unique(.$carb))
   }

-output

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

this works perfectly. Any chance you could explain what it does. Searching seems to only bring up r.markdown explanations.
@MorrisseyJ It is more easier to understand if you assign the output at the filter step to a new object i.e. d1 <- mtcars %>% filter(carb==4) then it is just ggplot(d1, aes(x = am, fill = gear)) + geom_bar(stat = 'count') + labs(title = unique(d1$carb)). Wrapping within a {} allows to consider it as a single block and we can extract the values of columns from the previous step i..e the 'carb' column

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.