Home > Enterprise >  generating plots inside a loop, using the pipe
generating plots inside a loop, using the pipe

Time:10-29

I want to generate plots inside a loop. I need to pipe in the data argument to ggplot like so:

data <- data.frame(a = c(1,2,3), b = c(5,8,9))

data %>% ggplot(aes(x=a, y=b))  
    geom_point()

When generating plots from inside a loop, we need to pass ggplot to print(), but this doesn't seem to play well when piping in the data argument:

# This works
for(i in 1:2){
  (ggplot(data, aes(x=a, y=b))  
    geom_point()) %>%
    print()
}

# This does not
for(i in 1:2){
  data %>%
  (ggplot(aes(x=a, y=b))  
     geom_point()) %>%
    print()
}

Is there a way to make the pipe play nice with the parentheses around the ggplot call?

CodePudding user response:

Try including data in the parentheses:

for(i in 1:2){
  (data %>%
  ggplot(aes(x=a, y=b))  
     geom_point()) %>%
    print()
}
  • Related